C++结构错误"No matching function for call..."

C++ Struct Error "No matching function for call..."

本文关键字:function for call matching No 结构 错误 C++      更新时间:2023-10-16

我目前有以下结构

struct LR0Item{
    string lhs;
    vector<string> rhs;
    int dpos;
};
struct Node{
    LR0Item* item;
    map<string, Node*> tr;
};
struct my_struct{
    bool operator()(
                    const LR0Item &a,
                    const LR0Item &b) {
                        if(a.lhs != b.lhs)
                            return a.lhs<b.lhs;
                        if(a.dpos != b.dpos)
                            return a.dpos<b.dpos;
                        return a.rhs<b.rhs;
                    }
};

和以下代码:

vector<string> test_v;              //assume this is filled with various strings
vector<Node*> N;
map<LR0Item,Node*,my_struct> nmap;
LR0Item* Q = new LR0Item("test", test_v, 3);     //1 - error occurs here
Node* N1 = new Node(Q);                          //2 - error occurs here
N.push_back(N1);
nmap[*Q] = N1;

我在评论1上得到一个错误,说:

error: no matching function for call to 'LR0Item::LR0Item(std::string&, std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&, int&)'|
note: candidates are: LR0Item::LR0Item()|
note:                 LR0Item::LR0Item(const LR0Item&)

我在评论2中的错误是:

error: no matching function for call to 'Node::Node(LR0Item*&)'
note: candidates are: Node::Node()|
note:                 Node::Node(const Node&)

我不完全确定这里发生了什么,也不知道如何解决。

编辑:为了澄清,不要使用C++11。

您需要为LR0Item创建一个构造函数,该构造函数与错误消息中指定的签名匹配:

LR0Item::LR0Item(std::string&, std::vector<std::basic_string<char,
  std::char_traits<char>, std::allocator<char> >,
  std::allocator<std::basic_string<char, std::char_traits<char>, 
  std::allocator<char> > > >&, int&)

简化模板并修复常量,当然这就是:

LR0Item::LR0Item(const std::string&, const std::vector<std::string>&, int)

您尚未为类创建构造函数

您似乎想要一个用于LR0Item(const String&,vector,int)和一个用于Node(const LR0Item&)

将此添加到LR0项目:

LR0Item(const String& lhs_p, vector<string> rhs_p, int dpos_p)
     : lhs(lhs_p), rhs(rhs_p), dpos(dpos_p) {}

并将其添加到节点:

Node(LR0Item * lr) : item(lr) {}

{}中添加初始化所需的任何其他操作

您可能也想使用复制构造函数,因为一旦定义了构造函数,您就不会有默认的

如果您想更深入地了解构造函数和重载operator =,请深入了解

在C++11中,您可以尝试以下操作:

// Brackets instead of parentheses
LR0Item* Q = new LR0Item{"test", test_v, 3};
Node* N1 = new Node{Q};
int main() {
N.push_back(N1);
nmap[*Q] = N1;
}

如果您有C++11编译器,那么只需将这些调用中的圆括号更改为大括号

否则,对于C++03编译器,请定义构造函数

相关文章: