我想要设计类似于以下的类结构。主要想法是必须在需要时更新基类指针。同样,我们可以在子类上进行一些不相关的操作。如何让子类包含指向基类的指针
我想知道如何重新设计这个具有多态性和封装。这可能是一个很noob问题,但任何帮助表示赞赏。
我不关心被剪切的内存泄漏,因为在实际代码中使用了这些代码,因此正在使用删除来避免任何问题。
我想问的是,有没有类似于下面的类结构更好的方法,而不是Child1调用getBase来获取基类指针,它可以扩展基类,其中基类可能已经已经实例化,child1只是封装并提供一些功能。
class Base {
private:
int a;
char b;
public:
Base(int argA, char argB): a(argA), b(argB) {
}
char getChar() {
return b;
}
int getInt() {
return a;
}
void setChar(char foo) {
b = foo;
}
void setInt(int foo) {
a = foo;
}
};
class Child1 {
private:
Base *base;
public:
Child1(PhysicalBlock *argBase) : base(argBase) {
}
Base *getBase() {
return base;
}
uint64_t getSum() {
int a = base->getInt();
char b = base->getChar();
return a + (int)b;
}
};
class Child2 {
private:
Base * base;
double c;
public:
Child2(Base * argBase) : base(argBase), c(0.0) {
}
Base *getBase() {
return base;
}
double getDivision() {
int a = base->getInt();
char b = base->getChar();
return (double) ((double)a + (double)b)/c;
}
};
int bla(Child1 * c1)
{
Base * b1 = c1->getBase();
b1->setInt(55);
b1->setChar('z');
return c1->getSum();
}
int main()
{
Base * b1 = new Base(1, 'a');
Base * b2 = new Base(2, 'b');
Child1 * child1 = new Child1(b1);
Child2 * child2 = new Child2(b2);
bla(child1);
return 0;
}
你为什么给我们展示'bla()'?哦,也许是这个'foo(child1);' - >'bla(child1);'?我也不明白你的问题。我的意思是我不认为你在问你的程序的内存泄漏... – gsamaras
你真的*试图实现什么?这听起来有点像[XY问题](http://xyproblem.info)。 –
@gsamaras已添加编辑。是的,这是一个错字。我指的是bla(child1) –