Re: [問題] template 用法
※ 引述《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
04/24 22:24, 1F
→
04/24 22:25, , 2F
04/24 22:25, 2F
→
04/24 22:26, , 3F
04/24 22:26, 3F
→
04/24 22:32, , 4F
04/24 22:32, 4F
→
04/24 22:33, , 5F
04/24 22:33, 5F
→
04/24 22:34, , 6F
04/24 22:34, 6F
→
04/24 22:35, , 7F
04/24 22:35, 7F
推
04/24 23:22, , 8F
04/24 23:22, 8F
→
04/24 23:22, , 9F
04/24 23:22, 9F
→
04/24 23:24, , 10F
04/24 23:24, 10F
→
04/24 23:36, , 11F
04/24 23:36, 11F
→
04/24 23:39, , 12F
04/24 23:39, 12F
→
04/24 23:39, , 13F
04/24 23:39, 13F
→
04/24 23:40, , 14F
04/24 23:40, 14F
推
04/24 23:57, , 15F
04/24 23:57, 15F
→
04/24 23:58, , 16F
04/24 23:58, 16F
→
04/24 23:58, , 17F
04/24 23:58, 17F
討論串 (同標題文章)