3
class A
{
    private:
        A () {}

    public:
        static A* getInstance ()
        {
            return new A ();
        }
};

int main ()
{
    A.getInstance ();
    return 0;
}

results in the error stated in the title. I do realize that if I create a variable in class A and instanciate it there and return it directly, the error will vanish.

But, here I want to understand what is the meaning of this error and why can't I use it this way.

4

5 に答える 5

12

You need to call the method using the scope resolution operator - :::

 A::getInstance ();

Also, if this is meant to be a singleton, it's a very bad one. Whenever you call getInstance(), you'll receive a new object, and you'll run into memory leaks if you forget to delete any instances.

A singleton is usually implemented like so:

class A
{
    private:
        A () {}
        static A* instance;
    public:
        static A* getInstance ()
        {
            if ( !instance )
                instance = new A ();
            return instance;
        }
};

//implementation file
A* A::instance = NULL;
于 2012-05-03T11:10:46.483 に答える
4

Use scope resolution operator :: (not . like in Java for example):

A::getInstance();
于 2012-05-03T11:11:11.550 に答える
2

getInstanceクラスの静的関数ですA。クラスの静的関数を呼び出す正しい形式はです<class_name>::<static_function_name>

.クラスのオブジェクトを作成し、演算子 を使用して静的関数を呼び出すこともできます。<class_object>.<static_function_name>

于 2012-05-03T11:23:53.107 に答える
1

.またはを使用して静的メンバー関数を呼び出すことができます::。ただし、クラス名を使用する場合は、後者とオブジェクトを使用する必要があり、前者を使用します。

于 2012-05-03T11:11:34.507 に答える
1

スコープ解決演算子を使用する::

例えば

class::methodName()
于 2012-05-03T11:12:46.377 に答える