[英]C++ call of overloaded constructor is ambiguous
假设我有这个虚拟类定义:
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)
因为它有不同的参数签名。
有一些我想念的东西:它是什么?
对Node :: Node()的调用对于Node :: Node(const int)不应该是模糊的,因为它具有不同的参数签名。
当然这是模棱两可的。 三思而后行!
你有
Node ();
Node (const int = 0);
当你调用Node()
时应该选择哪一个? 具有默认值参数的那个?
它应该工作而不提供默认值:
Node ();
Node (const int); // <<<<<<<<<<<<< No default
编译器无法知道您是否要使用默认值调用默认构造函数或int
构造函数。
你必须删除默认值或删除默认构造函数(它与你的构造函数使用int
做同样的事情,所以这不是一个真正的问题!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.