C++在小例子中不能直接调用构造函数

标签 c++ constructor

我想知道,为什么我不能调用构造函数。即使是这个小示例也无法编译并显示以下消息:

Klassentest.cpp:24:27: error: cannot call constructor 'Sampleclass::Sampleclass' directly [-fpermissive]

代码:

#include <iostream>
using namespace std;

class Sampleclass
{
   public:
    Sampleclass();
};

Sampleclass::Sampleclass(){

}

int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    Sampleclass::Sampleclass() *qs = new Sampleclass::Sampleclass();
    return 0;
}

我在版本 4.9.3-1 中使用了 Cygwin g++ 编译器。

感谢您的帮助。

最佳答案

Sampleclass::Sampleclass() *qs = new Sampleclass::Sampleclass();

错了。 Sampleclass 是一个类型,而Sampleclass::Sampleclass 是一个构造函数。因为正确的语法是

type identifier = new type();

您需要在此处指定类型

因此,使用

Sampleclass *qs = new Sampleclass();

相反。


注意事项:

  • 如果您不知道:从 C++11 开始您可以简单地做

    Sampleclass() = default;
    

    在类定义中会定义默认构造函数。

关于C++在小例子中不能直接调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34085147/

相关文章:

c++ - 返回指针或迭代器

c++ - 如何在 C++ 中使用带有模板的类型作为模板参数

c++ - 显式使用 main 中的构造函数调用作为函数调用参数

C++更改构造函数中的函数解析优先级

C++ 从指针构造

c++ - 并发 C++11 - 可以使用哪些工具链?

c++ - Qt 5.7.1/GCC 6.3.0:错误:constexpr函数的主体'静态constexpr int QMetaTypeId2 <T>

c++ - 函数调用中的段错误

Javascript子类代码解释

php - 使用错误的输入初始化类会使其无法使用,但对象仍然存在