gpt4 book ai didi

c++ 继承基类和子类

转载 作者:太空宇宙 更新时间:2023-11-04 15:44:00 25 4
gpt4 key购买 nike

这是我的基类 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 的 undefined reference ”。

我尝试自己进行一些调试。当我删除 Cross 构造函数时,它工作正常。但我绝对需要它。谁能给我解释一下?

最佳答案

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

添加

Shape::Shape()
{
}

或删除

Shape();

会修复它。


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

undefined reference to Shape::Shape()

关于c++ 继承基类和子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19594715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com