简体   繁体   English

重载构造函数的C ++调用是不明确的

[英]C++ call of overloaded constructor is ambiguous

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: 现在 ,如果我编译(使用选项: -Wall -Weffc++ -std=c++11 )代码如下:

#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. 据我所知(我正在学习C ++),对Node::Node()的调用不应该与Node::Node(const int)因为它有不同的参数签名。

There is something I am missing: What it is? 有一些我想念的东西:它是什么?

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()的调用对于Node :: Node(const int)不应该是模糊的,因为它具有不同的参数签名。

Sure that is ambiguous. 当然这是模棱两可的。 Think twice! 三思而后行!

You have 你有

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

which one should be selected when you call Node() ?? 当你调用Node()时应该选择哪一个? The one with the defaulted value parameter? 具有默认值参数的那个?

It should work without providing the default: 它应该工作而不提供默认值:

    Node ();
    Node (const int); // <<<<<<<<<<<<< No default

The compiler just cannot know if you want to call the default constructor or the int constructor with a default value. 编译器无法知道您是否要使用默认值调用默认构造函数或int构造函数。

You have to remove the default value or remove the default constructor (which does the same thing as your constructor with int so that's not really a problem!) 你必须删除默认值或删除默认构造函数(它与你的构造函数使用int做同样的事情,所以这不是一个真正的问题!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM