[英]C++ How to have an instance of the same class as an attribute?
I am trying to have a class called Cube have an attribute that is an instance of another cube. 我试图让一个名为Cube的类具有一个属性,该属性是另一个多维数据集的实例。
Here are the important parts of my Cube.cpp: 这是我的Cube.cpp的重要部分:
bool hasSon = false;
Cube* son;
Cube::Cube()
{
}
void Cube::setSon(Cube* s)
{
son = s;
hasSon = true;
}
void Cube::draw() {if(hasSon) {son->draw()}}
And here is my cube.h: 这是我的cube.h:
class Cube
{
public:
Cube();
bool hasSon;
Cube* son;
void setSon(Cube* son);
void draw();
};
I am instancing the cube and using setSon(); 我正在实例化多维数据集并使用setSon(); like so:
像这样:
Cube* base = new Cube();
Cube* base2 = new Cube();
base->setSon(base2);
The problem I am getting is that I get memory erros, even if I never call setSon();
我遇到的问题是,即使我从未调用过
setSon();
我也会遇到内存错误setSon();
what would be the correct way to set the son
attribute? 设置
son
属性的正确方法是什么?
Here is my error: 这是我的错误:
Exception thrown at 0x00DA3716 in CG_Demo.exe: 0xC0000005: Access violation reading location 0xCDCDCDF1.
Unhandled exception at 0x00DA3716 in CG_Demo.exe: 0xC0000005: Access violation reading location 0xCDCDCDF1.
You don't need hasSon
. 您不需要
hasSon
。 You can initialize the pointer to nullptr
and use that to test if a Cube*
has been set. 您可以初始化指向
nullptr
的指针,并使用它来测试是否已设置Cube*
。 As your provided code is incomplete its hard to say why you get the error, but this works, 由于您提供的代码不完整,因此很难说出为什么会出错,但这可以解决问题,
class Cube
{
public:
Cube();
//bool hasSon;
Cube* son;
void setSon(Cube* son);
void draw();
};
Cube::Cube() : son(nullptr)
{}
void Cube::setSon(Cube* s)
{
son = s;
}
void Cube::draw()
{
if(son)
son->draw();
}
int main()
{
Cube* base = new Cube();
Cube* base2 = new Cube();
base->setSon(base2);
base->draw();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.