首页 > 解决方案 > Pointer to the class instance

问题描述

I hane got a class inserted into the namespace:

namespace CPGL
{
    class Application;
}

class Application
{
    public:

        Application()
        {
            ...
        }
};

When I tryed to create a pointer this class like this:

CPGL::Application application();
CPGL::Application* app = &application;

Strange and mysterious things are started to happen. Here is the compilation log:

error: cannot convert ‘CPGL::Application (*)()’ to ‘CPGL::Application*’ in initialization
CPGL::Application* app = &application;

The question is how does a link to the class turned to a pointer to the constructor function of this class and how to solve it?

标签: c++classpointershyperlinkfunction-pointers

解决方案


CPGL::Application application();是一个函数声明,因此编译器诊断显示CPGL::Application (*)()

CPGL::Application application();
CPGL::Application* app = &application;

表达式&application在这里是一个函数指针。这个错误有时(错误地)被称为The most vexing parse

你可能想要的是

CPGL::Application application;
CPGL::Application* app = &application;

另请注意,您的命名空间声明了一个类Application,但它是在命名空间之外定义的。这可能是也可能不是问题中的错字。

我不想将其描述为最令人烦恼的解析,因为没有语法规则可以合理地允许将其作为对构造函数的调用。type name();是一个函数声明,句号。 A a(object of type B)然而,调用构造函数的正确方法是A::A(B b)。所以有理由认为它A a(B())创建了一个 B 类型的对象作为 A ctor 的参数。编译器将其解析为类型。这在链接的 SO 答案中进行了讨论。


推荐阅读