首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >cpp没有匹配函数调用构造函数。为什么?

cpp没有匹配函数调用构造函数。为什么?
EN

Stack Overflow用户
提问于 2019-01-15 04:47:35
回答 1查看 523关注 0票数 2

下面是我的代码:

代码语言:javascript
复制
// 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[])
{
}

当我试图使用以下方法编译它时:

代码语言:javascript
复制
g++ filename.cpp 

产生了下列产出:

代码语言:javascript
复制
$ 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

我不明白为什么会发生这种情况,因为我甚至没有调用构造函数,而是在定义函数的方法签名,用户应该能够将存在的状态对象传递到该方法签名中。请协助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-15 06:29:04

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

解决这个问题的方法有两种:

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

在这两种方法中,第二种方法更可取。在FAQ:我的构造函数应该使用“初始化列表”还是“赋值”?中列出了原因。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54192818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档