Re: [問題] template 用法

看板C_and_CPP作者 (非常念舊)時間9年前 (2016/04/24 22:12), 9年前編輯推噓2(2015)
留言17則, 4人參與, 最新討論串2/2 (看更多)
※ 引述《gn00618777 (非常念舊)》之銘言: : 最近在 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); 還比較容易理解.. : } : 謝謝 板友提供的關鍵字 copy initialization,讓我大概瞭解 int *ptr; Demo<int> p = ptr; --> 會去判斷等號右邊的型態,進而去尋找 Demo 中符合 的建構子,ptr 是一個指標,所以去 call Demo(T*other) 在Android源碼常會看到下面寫法 sp<Camera> c = new Camera(); 不太懂 c 的意義是甚麼,代表可以用c去存取 Camera類別內的方法嗎?我去試下面 範例 code Camera 用 myClass 取代, sp 用 Demo 取代 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; } class myClass{ public: myClass():a(0){} int getA(){return a} private: int a; }; int main(){ Demo<myClass> c = new myClass(); // call Demo(T * other) 建構子沒問題 cout<<c->getA()<<endl; // 這邊就錯了,也許我搞不清楚 c 到底是甚麼 // [Error] base operand of '->' has non-pointer type 'sp<myClass>' } 能否板友再指點我一下呢...謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 58.115.110.72 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1461507127.A.85C.html ※ 編輯: gn00618777 (58.115.110.72), 04/24/2016 22:14:35

04/24 22:24, , 1F
Demo class templace沒有getA的data member function
04/24 22:24, 1F

04/24 22:25, , 2F
跟template無關 純粹是你沒弄清楚物件的用法
04/24 22:25, 2F

04/24 22:26, , 3F
-> 是給指標用的. c不是指標當然不能用
04/24 22:26, 3F

04/24 22:32, , 4F
new 這個用法是傳回記憶體位址,所以我很自然的把 c
04/24 22:32, 4F

04/24 22:33, , 5F
當成一個指標去接這位址...
04/24 22:33, 5F

04/24 22:34, , 6F
以Demo<myClass> 宣告的 c 看起來是一個物件
04/24 22:34, 6F

04/24 22:35, , 7F
c 去接這個位址整個就不通
04/24 22:35, 7F

04/24 23:22, , 8F
我不知道android source code, 不過那個sp看起來就很像
04/24 23:22, 8F

04/24 23:22, , 9F
smart pointer?
04/24 23:22, 9F

04/24 23:24, , 10F
smart pointer會去overload -> operator
04/24 23:24, 10F

04/24 23:36, , 11F
是的,他是個smart point,也有看到它overload ->
04/24 23:36, 11F

04/24 23:39, , 12F
overload operator -> 的用法應該是 c-> 成員
04/24 23:39, 12F

04/24 23:39, , 13F
我不解的是 new myClass 這個記憶體位址,它在 sp 內
04/24 23:39, 13F

04/24 23:40, , 14F
它是如何被指定到 sp 類別的哪些成員變數或是某些操作
04/24 23:40, 14F

04/24 23:57, , 15F

04/24 23:58, , 16F
Built-in member access operators
04/24 23:58, 16F

04/24 23:58, , 17F
If a user-defined operator-> is provided ...
04/24 23:58, 17F
文章代碼(AID): #1N7DGtXS (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1N7DGtXS (C_and_CPP)