2016-02-13 112 views
3

在尋找二叉樹實現的示例時,我注意到代碼中提供了一些奇怪的東西here。在節點結構的構造函數一個非指針類型的變量被分配給一個指針類型。C++,將非指針類型賦值給模板類的成員指針

它編譯得很好(我正在使用GCC 5.3.0)。而讓我感到困惑的是編譯依賴於其他構造函數的參數,val

它在類中的方法沒有效果,只是在構造函數:

我越來越
template <typename T> 
class Test { 
    Test* testPtr; 

    void testMethod(T t, Test<T> notAPointer) { // OK 
     this->testPtr = notAPointer; 
    } 

    void testMethod(Test<T> notAPointer) {  // OK 
     this->testPtr = notAPointer; 
    } 

    Test(T t, Test<T> notAPointer) {   // OK 
     this->testPtr = notAPointer; 
    } 

    Test(Test<T> notAPointer) {     // compilation error 
     this->testPtr = notAPointer; 
    } 
}; 

的編譯錯誤是:

invalid constructor; you probably meant ‘Test (const Test&)’

這是爲什麼發生?標準中描述的這種行爲在哪裏?

+0

我認爲這是一個錯字。它編譯得很好,因爲所調用的構造函數沒有被調用。 – cpplearner

+0

構造'notAPointer'參數時調用哪個構造函數? – emlai

+0

您的構造函數的問題與指針分配或任何伴隨問題完全無關。你會得到與空的構造函數體相同的錯誤。複製構造函數無法通過值接收其參數 - 這就是它的全部內容,而這正是您的編譯器試圖告訴您的。 – AnT

回答

3

您最後的構造函數是copy constructor。禁止有一個拷貝構造函數按值傳遞它的參數,否則你會以無限遞歸結束。

你得到的錯誤是類似於

struct Foo 
{ 
    Foo(Foo); 
}; 

Live on Coliru

更確切地說,根據標準:

12.8/2複製和移動類對象[class.copy ]

A non-template constructor for class X is a copy constructor if its first parameter is of type X& , const X& , volatile X& or const volatile X& , and either there are no other parameters or else all other parameters have default arguments (8.3.6). [ Example: X::X(const X&) and X::X(X&,int=1) are copy constructors.

其他構造函數/成員函數似乎沒有問題,因爲它們沒有實例化,並且代碼在語法上是正確的(理論上,Test<T>對於某些專業化可能具有轉換運算符到T*,並且編譯器在實例化之前無法檢查)。然而,拷貝構造函數必須有一個確定的形式,這是由編譯器強制執行的。

1

你所有的例子都是無效的。當您嘗試實例化任何方法,你會得到一個編譯錯誤:

template <typename T> 
struct Test { 
    Test* testPtr; 

    void testMethod(Test<T> notAPointer) { 
     this->testPtr = notAPointer; 
    } 
}; 

int main() { 
    Test<int> t1, t2; 
    t1.testMethod(t2); // This line will cause the error. 

    return 0; 
} 

prog.cpp: In instantiation of 'void Test::testMethod(Test) [with T = int]': prog.cpp:16:18: required from here prog.cpp:9:23: error: cannot convert 'Test' to 'Test*' in assignment this->testPtr = notAPointer; ^