【发布时间】:2015-02-19 01:38:48
【问题描述】:
#include <iostream>
using namespace std;
class aclass
{
public:
int a;
};
class cclass: public aclass
{
public:
cclass()
{
a= //what do i write here//
}
}
class bclass : public aclass
{
public:
bclass()
{
a=9; //a is not constant here. I have just taken it const for simplicity.
}
int func();
};
int bclass::func()
{
cclass * ob;
ob = new cclass();
}
如何使 cclass 对象的变量 a 的值等于创建它的 bclass 对象(cclass 的对象)的 a 值。我可以在函数 func() 中做到这一点 通过做
ob->a = a;
但是在 cclass 的构造函数中我该怎么做呢?
【问题讨论】:
-
我会重新阅读书中的那一章
-
我写了一个答案,但随后将其删除,因为您似乎不了解您尝试编写的代码的基本原理。你在这里的目标是什么?
-
在您拥有
new cclass的地方,cclass类型尚未声明,因此这不是真正的代码。 -
@RyanHaining 在运行时,将创建 bclass 的不同对象,这些对象将具有不同的 a 值,这些对象(bclass 的对象)将创建 cclass 的相应对象。通过“对应”,我的意思是 cclass 的 a 的值将等于 bclass 的对象的 a 的值,bclass 的对象创建了一个 cclass 的对象。
标签: c++ oop object inheritance constructor