[問題] template 用法

看板C_and_CPP作者 (非常念舊)時間8年前 (2016/04/16 16:41), 編輯推噓5(507)
留言12則, 5人參與, 最新討論串1/2 (看更多)
最近在 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

04/16 21:25, , 1F
因為C++會作 Implicit convert
04/16 21:25, 1F

04/16 22:15, , 2F

04/16 22:15, , 3F
/language/copy_initialization
04/16 22:15, 3F

04/17 10:13, , 4F
Demo<T>operator=(p, Demo<T>(ptr)) 等效這樣
04/17 10:13, 4F

04/17 19:53, , 5F
我還是卡住==",看不太懂C大的。而且我宣告封裝類別
04/17 19:53, 5F

04/17 19:54, , 6F
Demo 用來宣告一個物件 p ,而這個 p 可以被指定為
04/17 19:54, 6F

04/17 19:54, , 7F
一個指標?
04/17 19:54, 7F

04/18 12:21, , 8F
Demo<T>::operator=(p, Demo<T>(ptr)) 等效這樣 上面打
04/18 12:21, 8F

04/18 12:21, , 9F
04/18 12:21, 9F

04/18 22:13, , 10F
樓上不對, 這個是二樓提的 copy initialization
04/18 22:13, 10F

04/18 22:13, , 11F
雖然寫 = 但跟 operator = 完全無關
04/18 22:13, 11F

04/18 22:14, , 12F
如果沒有型態直接 p = ptr; 才是 operator =
04/18 22:14, 12F
文章代碼(AID): #1N4VhJpw (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1N4VhJpw (C_and_CPP)