在 C++ 中创建默认构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13385963/
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 17:15:12  来源:igfitidea点击:

Create a default constructor in C++

c++default-constructor

提问by user1824239

This might be a stupid question but I can't find a lot of information on the web about creating your own default constructors in C++. It seems to just be a constructor with no parameters. However, I tried to create my default constructor like this:

这可能是一个愚蠢的问题,但我在网上找不到很多关于在 C++ 中创建自己的默认构造函数的信息。它似乎只是一个没有参数的构造函数。但是,我尝试像这样创建我的默认构造函数:

Tree::Tree()  {root = NULL;}

I also tried just:

我也试过:

Tree::Tree() {}

When I try either of these I am getting the error:

当我尝试其中任何一个时,我收到错误:

No instance of overloaded function "Tree::Tree" matches the specified type.

没有重载函数“Tree::Tree”的实例与指定的类型匹配。

I can't seem to figure out what this means.

我似乎无法弄清楚这意味着什么。

I am creating this constructor in my .cppfile. Should I be doing something in my header (.h) file as well?

我正在我的.cpp文件中创建这个构造函数。我也应该在我的头.h文件( ) 中做一些事情吗?

回答by Pete Becker

Member functions (and that includes constructors and destructors) have to be declared in the class definition:

成员函数(包括构造函数和析构函数)必须在类定义中声明:

class Tree {
public:
    Tree(); // default constructor
private:
    Node *root;

};

Then you can define it in your .cpp file:

然后你可以在你的 .cpp 文件中定义它:

Tree::Tree() : root(nullptr) {
}

I threw in the nullptrfor C++11. If you don't have C++11, use root(0).

我投入了nullptrC++11。如果您没有 C++11,请使用root(0).

回答by Kevin Katzke

C++11allows you to define your own default constructor like this:

C++11允许你像这样定义你自己的默认构造函数:

class A {  
    public:
        A(int);        // Own constructor
        A() = default; // C++11 default constructor creation
};

A::A(int){}

int main(){
    A a1(1); // Okay since you implemented a specific constructor
    A a2();  // Also okay as a default constructor has been created
}

回答by Dietmar Kühl

It isn't sufficient to create a definition for any member function. You also need to declarethe member function. This also applies to constructors:

为任何成员函数创建定义是不够的。您还需要声明成员函数。这也适用于构造函数:

class Tree {
public:
    Tree(); // declaration
    ...
};

Tree::Tree() // definition
    : root(0) {
}

As a side note, you should use the member initializer list and you should notuse NULL. In C++ 2011 you want to use nullptrfor the latter, in C++ 2003 use 0.

作为旁注,您应该使用成员初始值设定项列表,而不应该使用NULL. 在 C++ 2011 中你想使用nullptr后者,在 C++ 2003 中使用0.

回答by Josh Heitzman

Yes, you need to declare it in your header. For example place the following inside the declaration of the tree class.

是的,您需要在标题中声明它。例如,将以下内容放在树类的声明中。

class Tree {
    // other stuff...
    Tree();
    // other stuff...
};