2017-02-13 67 views
-1

以下代碼不起作用。我不知道爲什麼。這與隱式/顯式有什麼關係?這是否稱爲轉換?編譯器錯誤嘗試調用轉換構造函數

#include <type_traits> 

template<typename T> 
class A { 
public: 

    A(T x) {_x=x;} 
    template<typename T2> explicit A(const A<T2> &r) {} 
    template<typename T2> explicit A(A<T2> &r){} 
    template<typename T2> 
    void operator=(const A<T2>& rhs) { _x = rhs._x; } 
    template<typename T2> 
    void operator=(A<T2>& rhs) { _x = rhs._x; } 
    T _x; 
}; 

int main() { 
     const A<int> a(10); 
     A<int> b = a; 
     b = A<int>(5); 
     A<int> c(a); 
     b(a); // not working. why? 
} 

錯誤:G ++ 6

test.cpp: In function ‘int main()’: 
test.cpp:25:12: error: no match for call to ‘(A<int>) (const A<int>&)’ 
     b(a); // not working. why? 
+0

它是如何工作的? – NathanOliver

+0

編譯器錯誤。 –

+0

你的拷貝構造函數不接受'const'參數。你也期望用'operator()'調用'b'? – tadman

回答

2

我不知道你期望b(a);做什麼,但它不會做你想要的。一個對象只能被構造一次。它已經建成後,你不能重建它。當你做什麼時你有什麼b(a);是你嘗試打電話給班級operator()。由於你沒有一個你會得到一個編譯器錯誤。如果你想將b設置爲值a,那麼你需要

b = a; 
相關問題