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