我想做的是:
Sub
在Base
类中有一个类对象。Sub
类访问Base
类的变量基数
#include "Sub.h"
class Base
{
Sub subobject
int x;
}
子.h
#include Base // to acces x from .cpp file
class Sub: public Base
{
void changevar();
}
子.cpp
#include "Sub.h"
// I tried to include base in here but that did not work either
void Sub::changevar()
{
x++;
}
但是我不断收到未定义的基类和未定义的未声明的 x 错误。我该如何解决这个问题?
如果将子对象存储为指针会怎样?
你还需要
然而,基类引用子类似乎有点奇怪,它打破了继承的全部意义,如果您需要这样做,那么您应该重新考虑您所做的是否正确。
另请注意,Sub 将拥有自己的 Base 作为其一部分,因此子对象的 Base 部分将与外部 Base 不同。
例如,如果 Base 本身有一个名为 Y 的整数,那么我们将拥有 Base 的 Y,但对于子对象也有一个单独的 Y。
也许更好地解释为什么基类需要子类的副本?
粗略的代码草图:
基数
#include "Base.h"
class Sub;
class Base
{
public:
Sub* subobject;
Base();
~Base();
void createSub();
};
基础文件
#include "Base.h"
#include "Sub.h"
Base::Base()
{
subobject = new Sub();
}
Base::~Base()
{
delete subobject;
}
void Base::createSub()
{
if (subobject)
return;
subobject = new Sub();
}
子.h
#include "Base.h"
class Sub : public Base
{
void changevar();
int x = 0;
};
子.cpp
void Sub::changevar()
{
x++;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句