C++ 错误:'.' 之前的预期不合格 ID 令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10430147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:02:51  来源:igfitidea点击:

error: expected unqualified-id before ‘.’ token

c++compiler-errors

提问by Aquarius_Girl

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.

导致标题中所述的错误。我确实意识到如果我在 A 类中创建一个变量并在那里实例化它并直接返回它,错误就会消失。

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

但是,在这里我想了解这个错误的含义是什么,为什么我不能这样使用它。

回答by Luchian Grigore

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.

此外,如果这是一个单身人士,这是一个非常糟糕的。每当您调用 时getInstance(),您都会收到一个新对象,如果您忘记删除任何实例,就会遇到内存泄漏。

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;

回答by hmjd

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

使用范围解析运算符::.例如不像在 Java 中那样):

A::getInstance();

回答by Aquarius_Girl

getInstanceis a static function of class A. The right form of calling a static function of a class is <class_name>::<static_function_name>.

getInstance是 class 的静态函数A。调用类的静态函数的正确形式是<class_name>::<static_function_name>.

We can also call the static function by creating object of the class and using .operator: <class_object>.<static_function_name>

我们还可以通过创建类的对象并使用.运算符来调用静态函数: <class_object>.<static_function_name>

回答by dirkgently

You can call a static member function using either .or ::. However, if you use class name you need to use the latter and an object then use the former.

您可以使用.或调用静态成员函数::。但是,如果您使用类名,则需要使用后者,而对象则使用前者。

回答by Hemant Metalia

use scope Resolution Operator ::

使用范围解析运算符::

e.g.

例如

class::methodName()