0

这是我的基类 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

形状.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;
}

这是我的子类。交叉.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

交叉.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 构造函数时,它工作正常。但我绝对需要它。谁能给我解释一下?

4

2 回答 2

4

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

添加

Shape::Shape()
{
}

或删除

Shape();

会修复它。


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

undefined reference to Shape::Shape()
于 2013-10-25T16:17:00.187 回答
2

您已经为 声明了一个默认构造函数Shape,但没有在任何地方定义它。的默认构造函数Cross隐式使用它来初始化其基类。

您的选择是:

  • 定义构造函数,如果你想Shape默认构造;
  • 否则,删除声明并使用其他构造函数Cross进行初始化。Shape
于 2013-10-25T16:17:59.150 回答