c++ - 静态函数如何访问类的私有(private)成员函数(构造函数)

标签 c++ singleton private-members static-functions

我遇到了如下代码,它基本上是单例类的示例,其中我们将类构造函数设为私有(private),并提供一个静态公共(public)函数来在需要时创建该类的实例。

我的问题是,当我们在静态函数内调用new运算符创建单例类的对象时,那么肯定会调用该类的构造函数。我很困惑它是如何发生的,因为据我所知,静态函数只能访问类的静态成员和静态函数,那么它如何访问类的私有(private)函数(即本例中的构造函数)?

静态函数可以在不创建任何实例的情况下调用类的任何私有(private)或公共(public)成员函数吗?

#include <iostream>

using namespace std;

class Singleton
{
public:
    static Singleton *getInstance(); 

private:
    Singleton(){}
    static Singleton* instance;
};

Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance() 
{
    if(!instance) {
        instance = new Singleton(); //private ctor will be called
        cout << "getInstance(): First instance\n";
        return instance;
    }
    else {
        cout << "getInstance(): previous instance\n";
        return instance;
    }
}

int main()
{
    Singleton *s1 = Singleton::getInstance();
    Singleton *s2 = Singleton::getInstance();
    return 0;
}

但是当我编写如下示例代码时:

class Sample
{
    private:
        void testFunc()
        {
            std::cout << "Inside private function" <<std::endl;
        }
    public:
        static void statFunc()
        {
            std::cout << "Inside static function" <<std::endl;
            testFunc();
        }
};

int main()
{
    Sample::statFunc();

    return 0;
}

我在使用 g++ 时遇到编译错误:

file.cpp: In static member function ‘static void Sample::statFunc()’:
file.cpp:61: error: cannot call member function ‘void Sample::testFunc()’ without object. 

如果我们可以使用静态公共(public)函数访问类的私有(private)函数,那么为什么我会收到此错误?

最佳答案

上述代码之所以有效,是因为 getInstance() 的实现调用了不需要对象实例的构造函数。

静态成员函数属于类而不是对象。因此,在调用静态成员函数时,不存在对象的实例,因此无法访问 this 指针,因为不存在。如果要从静态函数访问非静态私有(private)成员函数,则需要将对象的引用传递给该函数。例如

例如

class foo {
    public:
          foo(int i) : myInt(i) {}
          static int myStaticMethod(foo & obj);
    private:
          int myInt;
    };

    int foo::myStaticMethod(foo & obj) {
          return obj.myInt;
    }

#include <iostream>


int main() {
foo f(1);
std::cout << foo::myStaticMethod(f);
return 0;
};

关于c++ - 静态函数如何访问类的私有(private)成员函数(构造函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40721770/

相关文章:

actionscript-3 - 访问 protected 或私有(private)属性(property)

PHP 类的私有(private)属性和方法

c++ - 如何确保迭代器模板参数与模板类的模板参数具有相同的数据类型

c++ - 如何让 VS2008 在 C++ 项目中使用 __cdecl 而不是 __thiscall?

c++ - 如何使用 c++ api 获取 rank 3 tensorflow::Tensor 的最大值的索引?

c++ - 海湾合作委员会错误?链接方法,断序列点

javascript - 使用 RequireJS 在单例和原型(prototype)范围之间切换

c++ - 使用什么代替静态变量

c# - 访问私有(private)嵌套类成员 C#

objective-c - 计划中的单例 NSDictionary 子类的替代方案