c++ - 缺少默认构造函数 - 但我没有调用它?

标签 c++ constructor rule-of-three

我正在编写一个 C++ 应用程序,其中我有一个带有两个嵌套结构的 Controller 类,在我的头文件中定义如下:

class Controller {
    struct help_message {   // controller.hpp, line 19
        std::string summary;
        std::string details;
        help_message(const std::string&, const std::string&);
    };

    struct player_command {
        cmd_t cmd;
        help_message help;
        // cmd_t is my own typedef, irrelevant for this question
        player_command(const cmd_t&, const help_message&);
    };

    // more members...
};

在我的源文件中,我有这个:

Controller::player_command::player_command(const Controller::cmd_t& c, const help_message& h) {
    cmd = c;
    help = h;
};

Controller::help_message::help_message(const std::string& s, const std::string& d) {
    summary = s;
    details = d;
};

我认为这很好,但是当我编译时,这就是我得到的(controller.cpp 第 12 行是上面源代码片段的第一行):

g++  -g -Wall -std=c++0x  -c -o controller.o controller.cpp
controller.cpp: In constructor ‘palla::Controller::player_command::player_command(void (palla::Controller::* const&)(const args_t&), const palla::Controller::help_message&)’:
controller.cpp:12:93: error: no matching function for call to ‘palla::Controller::help_message::help_message()’
controller.cpp:12:93: note: candidates are:
In file included from controller.cpp:7:0:
controller.hpp:22:3: note: palla::Controller::help_message::help_message(const string&, const string&)
controller.hpp:22:3: note:   candidate expects 2 arguments, 0 provided
controller.hpp:19:9: note: palla::Controller::help_message::help_message(const palla::Controller::help_message&)
controller.hpp:19:9: note:   candidate expects 1 argument, 0 provided
controller.hpp:19:9: note: palla::Controller::help_message::help_message(palla::Controller::help_message&&)
controller.hpp:19:9: note:   candidate expects 1 argument, 0 provided
make: *** [controller.o] Error 1

根据我的推断,编译器在某处试图调用 help_message 的默认构造函数,而该构造函数并不存在。然后它尝试将调用与我创建的构造函数以及生成的复制构造函数和赋值运算符进行匹配,并在参数数量上失败。

但是我的代码的哪一部分调用了默认构造函数?我该如何解决这个错误?

最佳答案

player_command()构造函数首先默认构造help,然后赋值给它:

Controller::player_command::player_command(const Controller::cmd_t& c, const help_message& h) {
    cmd = c;
    help = h;
};

将其更改为:

Controller::player_command::player_command(const Controller::cmd_t& c, const help_message& h)
:  cmd(c),
   help(h)
{
};

参见 Benefits of Initialization lists

关于c++ - 缺少默认构造函数 - 但我没有调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54910082/

相关文章:

c++ - 如何在 C++ 中减去两个位集

Java:在其他各种类中使用一个类的相同实例

c# - 写this.propertyName或只是propertyName之间的区别

c++ - C++11 的三法则变成五法则?

c++ - Visual Studio : how to create a project that would compile 2 exe files?

c++ - 构建 C++ 应用程序时 OSX 系统包含文件的默认路径是什么?

c++ - 复合数据结构和摆弄指针

c++ - 在构造函数中接受某些类型

c++ - C++ 中的资源是什么?