![](/img/trans.png)
[英]C++ | Derived class is accessing private members of the base class rather than its own private members
[英]Does C++ require you to initialize base class members from its derived class?
class Base {
public:
int a;
Base():a(0) {}
virtual ~Base();
}
class Derived : public Base {
public:
int b;
Derived():b(0) {
Base* pBase = static_cast<Base*>(this);
pBase->Base();
}
~Derived();
}
是对基类构造函数的调用是必需的,还是c ++会自动执行此操作? 例如C ++是否要求您从任何派生类初始化基类成员?
在派生类的构造函数被调用之前,基类的构造函数将被自动调用。
您可以使用初始化列表显式指定要调用的基本构造函数(如果有多个):
class Base {
public:
int a;
Base():a(0) {}
Base(int a):a(a) {}
};
class Derived {
public:
int b;
Derived():Base(),b(0) {}
Derived(int a):Base(a),b(0) {}
};
基类构造函数会自动调用(并在派生类构造函数之前)。 因此,您不必也不必尝试手动调用基本构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.