class base
{
private:
int a;
};
class base2
{
private:
int b;
};
class derived:public base,public base2
{
private:
int c;
};
main()
{
base b;
derived d;
cout<<size of(base)<<size of(base2)<<size of(derived);
}
因为 int a 和 int b 是私有(private)变量。所以它们不会在派生类中被继承。所以输出应该是 4 4 4 但它是 输出:4 4 12 为什么?
最佳答案
since
int a
andint b
are private variables.so they are not getting inherited inderived
class
这是错误的——它们当然会被继承,没有它们,基类中的代码将无法工作。只是 derived
无法访问它们,但它不会更改派生类的 sizeof
。
考虑你的例子的这个扩展:
class base {
private:
int a;
protected:
base() : a(123) {}
void showA() {cout << a << endl;}
};
class base2 {
private:
int b;
protected:
base2() : b(321) {}
void showB() {cout << b << endl;}
};
class derived:public base,public base2 {
private:
int c;
public:
derived() : c (987) {}
void show() {
showA();
showB();
cout << c << endl;
}
};
即使您的 derived
类无法读取或更改 a
和 b
,它也可以通过调用其基类中的相应函数来显示它们的值.因此,变量必须保留在那里,否则 showA
和 showB
成员函数将无法完成它们的工作。
关于c++ - 与 sizeof 派生类混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195387/