为什么我无法访问基类 A 的类 B 初始化列表中的成员?
class A
{
public:
explicit A(int a1):a(a1)
{
}
explicit A()
{
}
public:
int a;
public:
virtual int GetA()
{
return a;
}
};
class B : public A
{
public:
explicit B(int a1):a(a1) // wrong!, I have to write a = a1 in {}. or use A(a1)
{
}
int GetA()
{
return a+1;
}
};
class C : public A
{
public:
explicit C(int a1):a(a1)
{
}
int GetA()
{
return a-1;
}
};
最佳答案
A 的构造函数在 B 之前运行,并且隐式或显式地,前者构造 A 的所有实例,包括 a
成员。因此 B 不能在 a
上使用构造函数,因为该字段已经构造。您尝试使用的表示法准确地表明要在 a
上使用构造函数,而在这一点上它是不可能的。
关于c++ - 关于c++的派生问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1303890/