Sho*_*kie 9 c++ oop inheritance destructor c++11
我知道私有(当然还有公共)析构函数的用法.
我也知道在派生类中使用受保护的析构函数:
使用受保护的析构函数来防止通过基类指针销毁派生对象
但我已经尝试运行以下代码,它将无法编译:
struct A{
int i;
A() { i = 0;}
protected: ~A(){}
};
struct B: public A{
A* a;
B(){ a = new A();}
void f(){ delete a; }
};
int main()
{
B b= B();
b.f();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我明白了:
void B::f()':
main.cpp:9:16: error: 'A::~A()' is protected
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
如果我从f()内部调用A中的受保护方法,它将起作用.那么为什么叫d tor不同呢?
Lig*_*ica 12
protected doesn't mean that your B can access the members of any A; it only means that it can access those members of its own A base... and members of some other B's A base!
This is in contrast to private, whereby some object with type A can always invoke the private members of another object with type A.