[问题] 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