派生类可以访问私有静态成员函数
我有这样的代码,看起来它可以工作。我不知道为什么可以这样访问私有静态方法。
class Base
{
public:
static void f(){std::cout<<"in base\n";};
};
class Derived:private Base
{
};
int main()
{
Derived::f();
return 0;
}
I have a code like this, it seems it works. I have no idea why private static method can be accessed like this.
class Base
{
public:
static void f(){std::cout<<"in base\n";};
};
class Derived:private Base
{
};
int main()
{
Derived::f();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
被我尝试过的所有编译器(几个 g++ 版本、como online、IBM xlC)拒绝,除了 sun CC。我的猜测是这是你的编译器中的一个错误。
Refused by all compilers I've tried (several g++ version, como online, IBM xlC) excepted sun CC. My guess is that it is a bug in your compiler.
不可以,
f
不应通过Derived
访问(成员函数除外),因为Base
是私有继承的。 GCC 正确报告此错误:No,
f
should not be accessible viaDerived
(except a member function) asBase
is inherited privately. GCC correctly reports this error:在您的代码中,
f()
是私有继承的,因此您无法像f()
的可访问性错误那样访问它in your code
f()
is privately inherited so you can't access it like thisaccessibility error for
f()
在私有继承中,基类的所有成员都成为派生类的私有成员
派生类私有地从基类派生,因此有成员函数 Base::f()成为派生类的私有成员。类的 Private 成员无法从类外部访问(只能在类成员函数内部访问),因此代码无法干净地编译。
f() 是静态函数这一事实对继承和访问说明符的这些基本规则没有影响。 Base 中的非静态成员函数将显示相同的行为。
如果您的编译器编译此代码,那么它有一个错误,您应该报告该错误。
In Private Inheritance, All the members of the Base Class become Private memebers of the Derived Class
Class Derived derives Privately from Class Base, Hence the member function Base::f() becomes Private member of the Derived class. A Private member of an class cannot be accessed from outside the class(only accessible inside class member functions) Hence the code cannot compile cleanly.
The fact that f() is static function has no effect on these basic rules of inheritance and Access specifiers. A non static member function in Base would show the same behavior.
If your compiler compiles this code then it has a bug which you should report.