静态方法可以访问相同类的私有方法吗? [英] Can a Static method access a private method of the same class?

查看:256
本文介绍了静态方法可以访问相同类的私有方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于单例/命名构造函数,我有这个问题。在这两种情况下,实际的构造函数都是受保护的或私有的,都不能从外部访问它们。

I have this question because of the singleton/named constructor. In both cases, the real constructors are protected or private, neither of which can be accessed from outside.

例如,一个简短的命名构造函数是这样的:

For example, a short named constructor is this:

 class A
{
  public:
    static A createA() { return A(0); } // named constructor
  private:
    A (int x);
};
int main(void)
{
   A a = A::createA(); 
}

我认为静态方法只能访问静态数据成员或访问私有数据/通过现有对象的方法。
但是,在上面的代码中,私有构造函数 A()不是静态的,并且在调用它时,也不存在任何对象。
因此,我能想到的唯一解释是静态方法可以访问同一类的非静态私有方法。有人可以通过一些解释来肯定或否定我的想法吗?

I thought static method can only access static data member, or access private data/method via an existing object. However, in the above code, private constructor A() isn't static, and at the time it is being called, no object exists either. So the only explanation I can think of is that static method can access non-static private method of the same class. Can anyone please either affirm or negate my thought, possibly with some lines of explanations?

很抱歉,这太琐碎了,但是关键字太普遍了,我无法在数十个Google页面上找到答案。

I apologize if this is too trivial however the key words are too common and I wasn't able to find an answer in dozens of google pages. Thanks in advance.

推荐答案

静态成员函数具有与非静态成员函数相同的访问权限。因此,是的,它可以访问该类中的任何公共,受保护和私有变量。但是,您需要将类的实例传递给函数,以便函数能够访问成员。否则,静态函数只能直接访问该类中的任何其他静态成员。

A static member function has the same access rights as a non static member function. So yes, it can access any public, protected, and private variable in the class. However you need to pass an instance of the class to the function for the function to be able to access the member. Otherwise a static function can only directly access any other static member in the class.

这篇关于静态方法可以访问相同类的私有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆