[爆卦]template是什麼是什麼?優點缺點精華區懶人包

為什麼這篇template是什麼鄉民發文收入到精華區:因為在template是什麼這個討論話題中,有許多相關的文章在討論,這篇最有參考價值!作者gn00618777 (非常念舊)看板C_and_CPP標題Re: [問題] template ...

template是什麼 在 幼而圓 Queendergarten Instagram 的精選貼文

2021-02-19 15:44:53

【抽抽樂圓】來抽天下雜誌📖免費試閱3個月! 感謝 @commonwealth_magazine 邀請 參與這次《天下40週年「進步的軌跡」》活動 . 我選的文章是 天下雜誌609期 2016-10-26 《不只給兒童看的兒童劇》 https://www.cw.com.tw/article/5079...


※ 引述《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
Caesar08: Demo class templace沒有getA的data member function 04/24 22:24
bibo9901: 跟template無關 純粹是你沒弄清楚物件的用法 04/24 22:25
bibo9901: -> 是給指標用的. c不是指標當然不能用 04/24 22:26
gn00618777: new 這個用法是傳回記憶體位址,所以我很自然的把 c 04/24 22:32
gn00618777: 當成一個指標去接這位址... 04/24 22:33
gn00618777: 以Demo<myClass> 宣告的 c 看起來是一個物件 04/24 22:34
gn00618777: c 去接這個位址整個就不通 04/24 22:35
BlazarArc: 我不知道android source code, 不過那個sp看起來就很像 04/24 23:22
BlazarArc: smart pointer? 04/24 23:22
BlazarArc: smart pointer會去overload -> operator 04/24 23:24
gn00618777: 是的,他是個smart point,也有看到它overload -> 04/24 23:36
gn00618777: overload operator -> 的用法應該是 c-> 成員 04/24 23:39
gn00618777: 我不解的是 new myClass 這個記憶體位址,它在 sp 內 04/24 23:39
gn00618777: 它是如何被指定到 sp 類別的哪些成員變數或是某些操作 04/24 23:40
BlazarArc: http://preview.tinyurl.com/qfvm482 04/24 23:57
BlazarArc: Built-in member access operators 04/24 23:58
BlazarArc: If a user-defined operator-> is provided ... 04/24 23:58

你可能也想看看

搜尋相關網站