8

Let's say I have this dummy class definition:

    class Node
    {
    public:
        Node ();
        Node (const int = 0);
        int getVal();
    private:
        int val;
    };

And dummy constructor implementations for educational purposes only as well:

Node::Node () : val(-1)
{
    cout << "Node:: DEFAULT CONSTRUCTOR" << endl;
}


Node::Node(const int v) : val(v) 
{
    cout << "Node:: CONV CONSTRUCTOR val=" << v << endl;
}    

Now, if I compile (with options: -Wall -Weffc++ -std=c++11) the code below:

#include <iostream>
#include "node.h"
using namespace std;

int main()
{   
    Node n;
    return 0;
}

I get this error, and does not compile at all:

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 ();
  ^

I cannot understand why.

As far as I know (I am learning C++), a call to Node::Node() should not be ambiguous with respect to Node::Node(const int) because the have a different parameter signature.

There is something I am missing: What it is?

4

2 回答 2

11

对 Node::Node() 的调用对于 Node::Node(const int) 不应有歧义,因为它们具有不同的参数签名。

当然这是模棱两可的。三思而后行!

你有

    Node ();
    Node (const int = 0);

打电话的时候应该选哪一个Node()??具有默认值参数的那个?

它应该在不提供默认值的情况下工作:

    Node ();
    Node (const int); // <<<<<<<<<<<<< No default
于 2016-10-22T17:12:51.047 回答
4

编译器只是不知道您是要调用默认构造函数还是int具有默认值的构造函数。

您必须删除默认值或删除默认构造函数(它与您的构造函数做同样的事情,int所以这不是一个真正的问题!)

于 2016-10-22T17:12:58.697 回答