c++ - 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?
解决方案
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 答案中进行了讨论。
推荐阅读
- html - 如何在html上添加带有图像源的href
- javascript - 根据来自不同对象数组的属性和值过滤对象数组
- java - 当android应用程序未运行时调用react native javascript代码
- hadoop - 将增量文件写入 S3 (MinIO) - PySpark 2.4.3
- sql-server - SQL 中 OpenQuery 返回的部分数据
- r - 在多个条件下获取值
- java - 为什么会出现无限循环?
- python-3.x - 无法从循环输出浮点数创建列表
- javascript - 如何从数组中汇总对象的属性并将其存储到父对象?
- json - 从json中删除双引号