2016-10-22 84 views
3

比方說,我有這個虛擬的類定義:C++調用不明確

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)含糊不清,因爲它們具有不同的參數簽名。

我錯過了一些東西:它是什麼?

+1

提示:看看第二個構造函數的默認值。 – skypjack

+0

當然,這是真的。謝謝 :)。 – grd

回答

5

對於Node :: Node(const int)的調用不應該是模糊的,因爲它們具有不同的參數簽名。

當然這是不明確的。仔細想想!

你有

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

,當你調用一個Node()應該選擇?具有默認值參數的那個?

應該不提供默認的工作:

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

編譯器只是不知道,如果你想調用默認的構造函數或int構造函數的默認值。

你必須刪除默認值或刪除默認的構造函數(它做同樣的事情,你的構造與int所以這不是一個真正的問題!)