10

我知道私有(当然还有公共)析构函数的用途。

我也知道在派生类中使用受保护的析构函数:

使用受保护的析构函数来防止通过基类指针破坏派生对象

但我尝试运行以下代码,但无法编译:

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;
}

我得到:

void B::f()':
main.cpp:9:16: error: 'A::~A()' is protected

我错过了什么?

如果我从 f() 内部调用 A 中的受保护方法,它将起作用。那么,为什么称呼 d'tor 不一样呢?

4

1 回答 1

13

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.

于 2013-10-19T17:33:59.003 回答