#include <iostream>
class A {
public:
A(){
std::cout << " construct A(): c "<< c << '\n';
};
A(int x):c(x){
std::cout <<" construct A(int x): x and c "<<x<<" "<<c<< "\n";
};
~A(){};
protected:
int c;
void f();
};
void A::f(){
std::cout <<" A::f() "<< c << "\n";
}
class B: public A{
public:
B(){
std::cout << " construct B(): c "<< c << '\n';
};
B(int x){
std::cout <<" construct B(int x): x "<<x<<"\n";
};
~B(){};
void g();
};
void B::g()
{
int d=c; // allowed
std::cout <<" B::g() c and d: "<< c<<" "<<d << "\n";
f(); // allowed
}
int main () {
A a(4);
B b(4);
// a.f () ; // forbidden
b.g() ; // forbidden
}
construct A(int x): x and c 4 4
construct A(): c 0
construct B(int x): x 4
B::g() c and d: 0 0
A::f() 0
A类带参构造函数被调用之后,使用带参的构造函数初始化了一个B类,其中B类构造函数初始化前自动调用了A的无参构造函数。因此重置了保护变量c?
如果要避免初始化派生类时重新初始化父类该怎么办?