1 template<class T>
 2 class ye
 3 {
 4 public:
 5     ye(){cout<<"I'm ye()"<<endl;}
 6 
 7     //-------------------------------
       //普通拷贝构造函数
 8     ye(const ye<T>&y){cout<<"I'm ye(const ye<T>&)"<<endl;}
       //模板拷贝构造函数
 9     template<class K>
10     ye(const ye<K> &){cout<<"I'm template<class K>ye(const ye<K>&)"<<endl;}
11     //-------------------------------
12 
13     //-------------------------------
14     ye(T*)
15     {
16         cout<<"I'm ye(T*)"<<endl;
17     }
18     template<class Y>
19     ye(Y*){cout<<"I'm template<class Y> ye(Y*)"<<endl;}
20     //-------------------------------
21 
22     //-------------------------------
23     ye& operator=(const ye<T> &)
24     {
25         cout<<"I'm operator=(const ye<T>&)"<<endl;
26         return *this;
27     }
28     template<class N>
29     ye& operator=(const ye<N> &)
30     {
31         cout<<"I'm template<class N> operator=(const ye<N>&)"<<endl;
32         return *this;
33     }
34     //-------------------------------
35 
36 };

上面是一个典型的模板类 首先看构造函数
当我们输入
ye<int> y;                 //输出I'm ye()
ye<int> k=y;或ye<int> k(y);//输出
I'm ye(const ye<T>&)
ye<float> f=k;             //输出
I'm template<class K>ye(const ye<K>&)
到此 没什么问题

现在注释掉两个拷贝构造函数
输入
ye<int> y;   //输出
I'm ye()
ye<int> k=y; //无输出,使用默认的构造函数

清空 输入
ye<int> y;    
ye<float> k=y; //会出现编译错误

清空 输入
ye<int> y;
ye<int> k;
y=k;         //I'm operator=(const ye<T>&)
ye<float> h;
h=k;         //I'm template<class N> operator=(const ye<N>&)

如果把操作符重载函数注释掉
当出现y=k时 就会调用相应默认的赋值函数
当出现h=k时 就会出现编译错误


posted on 2010-08-09 16:23 野猪红 阅读(928) 评论(0)  编辑 收藏 引用 所属分类: C/C++ STL Python Lua

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理