派生类可以访问私有静态成员函数

发布于 2024-11-01 05:14:59 字数 232 浏览 0 评论 0原文

我有这样的代码,看起来它可以工作。我不知道为什么可以这样访问私有静态方法。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

简单爱 2024-11-08 05:14:59

被我尝试过的所有编译器(几个 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.

葬花如无物 2024-11-08 05:14:59

不可以,f 不应通过 Derived 访问(成员函数除外),因为 Base 是私有继承的。 GCC 正确报告此错误:

temp.cpp:6: error: ‘static void Base::f()’ is inaccessible
temp.cpp:17: error: within this contex

No, f should not be accessible via Derived (except a member function) as Base is inherited privately. GCC correctly reports this error:

temp.cpp:6: error: ‘static void Base::f()’ is inaccessible
temp.cpp:17: error: within this contex
流云如水 2024-11-08 05:14:59

在您的代码中, f() 是私有继承的,因此您无法像

int main()
{

   Derived::f();
   return 0;
}

f() 的可访问性错误那样访问它

in your code f() is privately inherited so you can't access it like this

int main()
{

   Derived::f();
   return 0;
}

accessibility error for f()

给不了的爱 2024-11-08 05:14:59

在私有继承中,基类的所有成员都成为派生类的私有成员

派生类私有地从基类派生,因此有成员函数 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文