c++ - cpp 没有匹配的函数调用来调用构造函数。为什么?

标签 c++ class constructor

下面是我的代码:

// this code illustrates iterating through a nested hashmap.
#include <iostream>
#include "imported.hpp"
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
#define MAX_LINE_LENGTH 999

using namespace std;

class State
{

  public:
    vector<string> vec;
    string state_string;
    State(string state_string, vector<string> vec);
};

State::State(string state_string, vector<string> vec)
{
    this->state_string = state_string;
    this->vec = vec;
}

class Heuristic
{

  public:
    State goal_state;
    string type;
    Heuristic(string type, State goal_state);
};

Heuristic::Heuristic(string type, State goal_state)
{
    this->type = type;
    this->goal_state = goal_state;
}

int main(int argc, char const *argv[])
{
}

当我尝试使用以下方式编译它时:

g++ filename.cpp 

产生以下输出:

$ g++ main.cpp
main.cpp: In constructor ‘Heuristic::Heuristic(std::string, State)’:
main.cpp:36:51: error: no matching function for call to ‘State::State()’
 Heuristic::Heuristic(string type, State goal_state)
                                                   ^
main.cpp:21:1: note: candidate: State::State(std::string, std::vector<std::basic_string<char> >)
 State::State(string state_string, vector<string> vec)
 ^~~~~
main.cpp:21:1: note:   candidate expects 2 arguments, 0 provided
main.cpp:12:7: note: candidate: State::State(const State&)
 class State
       ^~~~~
main.cpp:12:7: note:   candidate expects 1 argument, 0 provided
main.cpp:12:7: note: candidate: State::State(State&&)
main.cpp:12:7: note:   candidate expects 1 argument, 0 provided

我很困惑为什么会发生这种情况,因为我什至没有调用构造函数,而是定义了一个函数的方法签名,用户应该能够将现有的 State 对象传递到该方法签名中。请协助。

最佳答案

Heuristic 构造函数是使用赋值运算符构建的,它涉及其成员对象的默认构造。由于 State 没有默认构造函数,因此这种构造形式将失败。

有两种解决方法:

  1. 如果成员有用户定义的构造函数,也为它们提供默认构造函数。
  2. 为您的构造函数使用初始化列表,而不是在构造函数体内进行赋值。

这两种方法中,第二种方法更可取。常见问题解答中概述了其原因:Should my constructors use “initialization lists” or “assignment”?

关于c++ - cpp 没有匹配的函数调用来调用构造函数。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54192818/

相关文章:

C++构造函数的使用和错误?

c++ - boost::multi_array 上的段错误

c++ - VS2010中的boost::function:错误C2039: 'function':不是 'boost'的成员

c++ - QUdpSocket 绑定(bind)失败

java - 加载另一个类时 Jpanel 不绘制

scala - 在需要函数的地方使用构造函数

C++ 调整/优化

python - 如何在Python中为类设置字符串渲染方法

c# - 如何从类中的函数使用 C# 访问 MySQL 数据库?

python - 为什么我的 Frame 子类在 init 中抛出错误?