[問題] template 用法

作者: gn00618777 (非常念舊)   2016-04-16 16:41:52
最近在 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); 還比較容易理解..
}
謝謝
作者: layan (教練我想打球 T_T)   2016-04-16 21:25:00
因為C++會作 Implicit convert
作者: suhorng ( )   2016-04-16 22:15:00
http://en.cppreference.com/w/cpp/language/copy_initialization
作者: CoNsTaR ((const *))   2016-04-17 10:13:00
Demo<T>operator=(p, Demo<T>(ptr)) 等效這樣
作者: gn00618777 (非常念舊)   2016-04-17 19:53:00
我還是卡住==",看不太懂C大的。而且我宣告封裝類別Demo 用來宣告一個物件 p ,而這個 p 可以被指定為一個指標?
作者: CoNsTaR ((const *))   2016-04-18 12:21:00
Demo<T>::operator=(p, Demo<T>(ptr)) 等效這樣 上面打錯
作者: LPH66 (-6.2598534e+18f)   2016-04-18 22:13:00
樓上不對, 這個是二樓提的 copy initialization雖然寫 = 但跟 operator = 完全無關如果沒有型態直接 p = ptr; 才是 operator =

Links booklink

Contact Us: admin [ a t ] ucptt.com