Re: [問題] template 用法

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

Links booklink

Contact Us: admin [ a t ] ucptt.com