重载构造函数的 C++ 调用不明确
C++ call of overloaded constructor is ambiguous
假设我有这个虚拟 class 定义:
class Node
{
public:
Node ();
Node (const int = 0);
int getVal();
private:
int val;
};
以及仅用于教育目的的虚拟构造函数实现:
Node::Node () : val(-1)
{
cout << "Node:: DEFAULT CONSTRUCTOR" << endl;
}
Node::Node(const int v) : val(v)
{
cout << "Node:: CONV CONSTRUCTOR val=" << v << endl;
}
现在,如果我编译(使用选项:-Wall -Weffc++ -std=c++11
)下面的代码:
#include <iostream>
#include "node.h"
using namespace std;
int main()
{
Node n;
return 0;
}
我收到这个错误,根本无法编译:
node_client.CPP: In function ‘int main()’:
node_client.CPP:10:16: error: call of overloaded ‘Node()’ is ambiguous
Node n;
^
node_client.CPP:10:16: note: candidates are:
In file included from node_client.CPP:4:0:
node.h:14:5: note: Node::Node(int)
Node (const int = 0);
^
node.h:13:2: note: Node::Node()
Node ();
^
我不明白为什么。
据我所知(我正在学习 C++),对 Node::Node()
的调用对于 Node::Node(const int)
不应含糊不清,因为它们具有不同的参数签名。
我缺少一些东西:它是什么?
a call to Node::Node() should not be ambiguous with respect to Node::Node(const int) because the have a different parameter signature.
当然是模棱两可的。三思而后行!
你有
Node ();
Node (const int = 0);
调用时应该选择哪一个Node()
??带默认值参数的那个?
它应该在不提供默认值的情况下工作:
Node ();
Node (const int); // <<<<<<<<<<<<< No default
编译器无法知道您是要调用默认构造函数还是使用默认值调用 int
构造函数。
您必须删除默认值或删除默认构造函数(它与使用 int
的构造函数做同样的事情,所以这不是真正的问题!)
假设我有这个虚拟 class 定义:
class Node
{
public:
Node ();
Node (const int = 0);
int getVal();
private:
int val;
};
以及仅用于教育目的的虚拟构造函数实现:
Node::Node () : val(-1)
{
cout << "Node:: DEFAULT CONSTRUCTOR" << endl;
}
Node::Node(const int v) : val(v)
{
cout << "Node:: CONV CONSTRUCTOR val=" << v << endl;
}
现在,如果我编译(使用选项:-Wall -Weffc++ -std=c++11
)下面的代码:
#include <iostream>
#include "node.h"
using namespace std;
int main()
{
Node n;
return 0;
}
我收到这个错误,根本无法编译:
node_client.CPP: In function ‘int main()’:
node_client.CPP:10:16: error: call of overloaded ‘Node()’ is ambiguous
Node n;
^
node_client.CPP:10:16: note: candidates are:
In file included from node_client.CPP:4:0:
node.h:14:5: note: Node::Node(int)
Node (const int = 0);
^
node.h:13:2: note: Node::Node()
Node ();
^
我不明白为什么。
据我所知(我正在学习 C++),对 Node::Node()
的调用对于 Node::Node(const int)
不应含糊不清,因为它们具有不同的参数签名。
我缺少一些东西:它是什么?
a call to Node::Node() should not be ambiguous with respect to Node::Node(const int) because the have a different parameter signature.
当然是模棱两可的。三思而后行!
你有
Node ();
Node (const int = 0);
调用时应该选择哪一个Node()
??带默认值参数的那个?
它应该在不提供默认值的情况下工作:
Node ();
Node (const int); // <<<<<<<<<<<<< No default
编译器无法知道您是要调用默认构造函数还是使用默认值调用 int
构造函数。
您必须删除默认值或删除默认构造函数(它与使用 int
的构造函数做同样的事情,所以这不是真正的问题!)