2

可能重复:
不能调用基类保护函数?

在 g++ 下编译:

class A
{
protected:
    void f(){}
};

class B: public A
{
    void g()
    {
        A a;
        f(); //This works
        a.f(); //Error: "A::F() is protected"
        this->f(); //Works
        ((A*)this)->f(); //Same error
    }
};

为基类的非 this 对象调用受保护函数时出错。编译器是 GCC - 但相同的代码在其他风格的 GCC 下工作。请问这是怎么回事 - 因为当调用基类的受保护方法时,verboten除非它是 via this

编辑:对不起,我的错。这都是规范;在它起作用的另一个地方,有一种我没有注意到的友谊。请投票关闭。

4

2 回答 2

1

You're calling function f() from the instance A. f() is a private function of B so from within B, you can do something like:

this->f() 

But if you make a new instance of A like you did and then call its f(), it's protected.

于 2012-12-18T22:09:22.413 回答
1

您不必f通过this- 您可以从任何类型的对象访问它B。例如,这将在内部工作B::g

B b;
b.f();

C++03 标准说 (11​​.5):

当派生类的友元或成员函数引用基类的受保护非静态成员函数或受保护非静态数据成员时,除了前面第 11 节中描述的那些之外,还应用访问检查。除非形成指向成员的指针(5.3 .1),访问必须通过派生类本身(或从该类派生的任何类)的指针、引用或对象

所以你可以f从一个对象类型B或派生对象访问B——包括但不限于*this.

C++11 标准包含类似的限制 (11.4)

于 2012-12-18T22:14:06.557 回答