c ++继承库和子类

时间:2013-10-25 16:11:19

标签: c++

这是我的基类Shape.h

#ifndef Shape_H
#define Shape_H

#include <iostream>
using namespace std;

class Shape
{
    protected:
    string name;
    bool containsObj;

public:
    Shape();
    Shape(string, bool);
    string getName();
    bool getContainsObj();
    double computeArea();
};

   #endif

Shape.cpp

#include "Shape.h"

Shape::Shape(string name, bool containsObj)
{
    this -> name = name;
    this -> containsObj = containsObj;
}
string Shape:: getName()
{
return name;
}
bool Shape::getContainsObj()
{
    return containsObj;
}

这是我的子类。 Cross.h

#ifndef Cross_H
#define Cross_H

#include <iostream>
#include "Shape.h"
using namespace std;

class Cross: public Shape
{
protected:
    int x[12];
    int y[12];
public:
    Cross();
    double computeArea();

};

#endif

Cross.cpp

#include "Cross.h"

Cross::Cross()
{

    for (int i = 0; i < 12; i++)
    {
        this -> x[i] = 0;
        this -> x[0] = 0;
    }

}

Shape和Cross位于不同的文件中,但位于同一文件夹中。奇怪的是当我编译它时,出现了我以前从未见过的错误,例如“在函数中'ZN5CrossC1Ev',对Shape :: Shape()的未定义引用,'ZN5CrossC1Ev',对Shape :: Shape()的未定义引用,未定义的引用WinMain @ 16“。

我试着自己做一些调试。当我删除Cross构造函数时,它工作正常。但我绝对需要它。任何人都可以向我解释这个吗?

2 个答案:

答案 0 :(得分:4)

您没有定义默认构造函数,但是您将其声明为Shape();。您定义的唯一构造函数是具有stringbool参数Shape(string, bool);的构造函数。

添加

Shape::Shape()
{
}

或删除

Shape();

会解决它。


为了将来的调试,请更仔细地阅读错误,它解释了错误的错误:

undefined reference to Shape::Shape()

答案 1 :(得分:2)

您已为Shape声明了默认构造函数,但未在任何位置定义它。 Cross的默认构造函数隐式使用它来初始化其基类。

您可以选择:

  • 如果您希望Shape是默认可构造的,则定义构造函数;
  • 否则,删除声明并获取Cross以使用其他构造函数初始化Shape
相关问题