看板 C_and_CPP 關於我們 聯絡資訊
最近在 trace android 的 code ,裡面有些 c++ 的程式,寫了一小段來驗證 #include<iostream> #include<stdlib.h> using namespace std; template<typename T> class Demo{ public: Demo(T* other); Demo(const Demo<T>& other); }; template<typename T> Demo<T>::Demo(T* other){ cout<<"This is the First constructor"<<endl; } template<typename T> Demo<T>::Demo(const Demo<T>& other){ cout<<"This is the second constructor"<<endl; } int main(){ int *ptr; Demo<int> p; // 會 error,因為它會找不到 Demo() 建構子,這個合理~ Demo<int> p = ptr; //這邊他會 call Demo(T* other) 這邊的建構子 //不太懂為啥他會call 第一個建構子呢? //如果用 Demo<int> p(ptr); 還比較容易理解.. } 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 58.115.110.72 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1460796115.A.CFA.html
layan: 因為C++會作 Implicit convert 04/16 21:25
suhorng: http://en.cppreference.com/w/cpp 04/16 22:15
suhorng: /language/copy_initialization 04/16 22:15
CoNsTaR: Demo<T>operator=(p, Demo<T>(ptr)) 等效這樣 04/17 10:13
gn00618777: 我還是卡住==",看不太懂C大的。而且我宣告封裝類別 04/17 19:53
gn00618777: Demo 用來宣告一個物件 p ,而這個 p 可以被指定為 04/17 19:54
gn00618777: 一個指標? 04/17 19:54
CoNsTaR: Demo<T>::operator=(p, Demo<T>(ptr)) 等效這樣 上面打 04/18 12:21
CoNsTaR: 錯 04/18 12:21
LPH66: 樓上不對, 這個是二樓提的 copy initialization 04/18 22:13
LPH66: 雖然寫 = 但跟 operator = 完全無關 04/18 22:13
LPH66: 如果沒有型態直接 p = ptr; 才是 operator = 04/18 22:14