没有匹配的函数调用头文件中的构造函数

时间:2017-10-20 04:45:16

标签: c++ c++11

我已经看到了类似的问题,并尝试了他们的解决方案,但他们的答案似乎不起作用。我有以下代码:

·H

#include <iostream>
#include <vector>
#include <string>
using std::string; using std::vector;

struct DialogueNode;

struct DialogueOption   {
    string text;
    DialogueNode *next_node;
    int return_code;

    DialogueOption(string t, int rc, DialogueNode * nn) : text{t}, 
        return_code{rc}, next_node{nn}   {}
};

struct DialogueNode {
    string text;
    vector <DialogueOption> dialogue_options;
    DialogueNode();
    DialogueNode(const string &);
};

struct DialogueTree {
    DialogueTree()  {}
    void init();
    void destroyTree();

    int performDialogue();
private:
    vector <DialogueNode*> dialogue_nodes;
};

的.cpp

#include "dialogue_tree.h"

DialogueNode::DialogueNode(const string &t) : text{t} {}

void DialogueTree::init()   {
    string s = "Hello";
    for(int i = 0; i < 5; i++)  {
        DialogueNode *node = new DialogueNode(s);
        dialogue_nodes.push_back(node);
        delete node;
    }
}

void DialogueTree::destroyTree()    {

}

int DialogueTree::performDialogue() {
    return 0;
}

int main()  {
    return 0;
}

我收到错误:error: no matching function for call to ‘DialogueNode:: DialogueNode(std::__cxx11::string&)’ DialogueNode *node = new DialogueNode(s);

编辑有关错误的其他说明

dialogue_tree.h:17:8: note: candidate: DialogueNode::DialogueNode()
dialogue_tree.h:17:8: note:   candidate expects 0 arguments, 1 provided
dialogue_tree.h:17:8: note: candidate: DialogueNode::DialogueNode(const DialogueNode&)
dialogue_tree.h:17:8: note:   no known conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘const DialogueNode&’
dialogue_tree.h:17:8: note: candidate: DialogueNode::DialogueNode(DialogueNode&&)
dialogue_tree.h:17:8: note:   no known conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘DialogueNode&&’

这对我没有意义,因为我已经定义了构造函数以string作为参数。

2 个答案:

答案 0 :(得分:2)

您已将构造函数声明为:

DialogueNode(const string);

但定义为:

DialogueNode(const string &t);

这两者并不相同;前者需要const string而后者需要const string引用。您必须添加&以指定引用参数:

DialogueNode(const string &);

答案 1 :(得分:0)

这是因为在构造函数中,您指定参数将是常量类型的字符串,并且在创建对象时传递字符串。类型不匹配是问题,要么将构造函数参数修复为字符串,要么在创建对象时更改。