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

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

问题描述:

我看过类似的问题,并尝试了他们的解决方案,但是他们的答案似乎不起作用。我有以下代码:没有匹配的函数调用头文件中的构造函数调用

.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作为参数。

+0

可能不相关,但是'dialogue_nodes'是什么?看起来你还没有显示_relevant_代码 – P0W

+0

@ P0W它是'DialogueTree'类中的'DialogueNode'指针的向量,我将附加该snipper代码 – quantik

+2

尽我所能,用不完整的代码,[无法重现] (https://wandbox.org/permlink/QnxPYc3STZWa9XSx)。 – chris

你宣布你的构造函数:

DialogueNode(const string); 

但将其定义为:

DialogueNode(const string &t); 

这两个是不一样的;前者需要const string而后者需要const string参考。你必须添加&指定引用参数:

DialogueNode(const string &); 
+0

给出了相同的错误 – quantik

+0

啊哈,你刚才在编辑中加了'&'。 – frslm

+0

是的,原来我不是参考,它给了我同样的问题。我决定做出改变,并没有完全更新程序。这并没有解决问题 - 不幸的是.. – quantik

这是因为在构造您所指定的参数将保持不变类型的字符串,并创建一个对象,当你传递一个字符串。类型不匹配是问题,或者将构造函数参数修复为字符串,或者在创建对象时进行更改。

+0

我更新了问题,但不能解决问题 – quantik

+2

非常量参数可以匹配常量参数(无论参数是否为引用)。这不是问题。 – aschepler

+0

感谢您加入我的知识! –