• 模板类的拷贝构造函数和重载=


     http://bbs.csdn.net/topics/190144045

    1
    #include<iostream> 2 #include<vector> 3 #include<string> 4 5 6 using namespace std; 7 8 template <typename T,size_t size> 9 class fixed_vector 10 { 11 public: 12 typedef T* iterator; 13 typedef const T* const_iterator; 14 fixed_vector() 15 { 16 cout<<"默认构造函数"<<endl; 17 } 18 19 20 template<typename T2,size_t osize> //如果模板函数的T和类的T可能不是一个类型的话,那么两个T要命名成不同的名字 (否则在linux下编译不成功. 在vs2010下可以同名) 21 fixed_vector( const fixed_vector<T2,osize>& other) 22 { 23 cout<<"模板拷贝构造函数1"<<endl; 24 } 25 26 fixed_vector( const fixed_vector& other) 27 { 28 cout<<"模板拷贝构造函数2"<<endl; 29 } 30 31 template <typename T2,size_t osize> 32 fixed_vector<T2,size>& operator=(const fixed_vector<T2,osize>& other) //注意这里返回的是size而不是osize 33 { 34 cout<<"模板赋值函数1"<<endl;//这不是真的赋值函数 35 return *this; 36 } 37 38 fixed_vector<T,size>& operator=(const fixed_vector& other) //注意这里返回的是size而不是osize 39 { 40 cout<<"模板赋值函数2"<<endl;//这不是真的赋值函数 41 return *this; 42 } 43 44 iterator begin() 45 { 46 return m_v; 47 } 48 iterator end() 49 { 50 return m_v+size; 51 } 52 53 const_iterator begin() const 54 { 55 return m_v; 56 } 57 58 const_iterator end() const 59 { 60 return m_v+size; 61 } 62 63 private: 64 T m_v[size]; 65 }; 66 67 68 int main() 69 { 70 cout<<"--------begin <char, 4>----------"<<endl; 71 fixed_vector<char,4> fv_char; 72 cout<<"--------begin <int , 4>----------"<<endl; 73 fixed_vector<int,4> fc_int1; 74 cout<<"--------begin <int, 8>(<int , 4>)----------"<<endl; 75 fixed_vector<int,8> fc_int2(fc_int1);//这里将调用模板拷贝构造函数 76 cout<<"--------begin <int, 8> = <int , 4>----------"<<endl; 77 fc_int2=fc_int1;//这里将调用模板赋值函数 78 79 cout<<"--------begin <int , 4>----------"<<endl; 80 fixed_vector<int,4> fc_int3; 81 cout<<"--------begin <int, 4>(<int , 4>)----------"<<endl; 82 fixed_vector<int,4> fc_int4(fc_int3);//这里不会调用模板拷贝构造函数 83 cout<<"--------begin <int, 4> = <int , 4>----------"<<endl; 84 fc_int3=fc_int4;//不调用模板赋值函数 85 86 //system("pause"); 87 return 0; 88 }

    ---------------------------------------------------------------------------------------------------------------------------

    http://blog.chinaunix.net/uid-7448695-id-2626460.html

    昨天看《Exceptional C++》,发现一个从来没有注意到标准(C++ 标准 12.8/2,note 4):“模板构造函数永远都不能成为拷贝构造函数”。所以模板构造函数永远不能取代拷贝构造函数,即便有了模板构造函数,默认拷贝构造函数还是会合成的。

      例如:

    class A
    {
    public:
      // 这个构造函数不会掩盖默认拷贝构造函数
      template <T>
      A (const T& t) {}
    };


      同样的情况对于 operator=() 一样适合。也就是模板赋值函数不会覆盖默认拷贝赋值函数。

    [美] Sutter, Hurb 著;聂雪军 译。《Exceptional C++ 中文版》。北京:机械工业出版社,2007 年 1 月第 1 版。第 11 页。

  • 相关阅读:
    Spring Cloud 入门教程6、Hystrix Dashboard监控数据聚合(Turbine)
    Spring Cloud 入门教程5、服务容错监控:Hystrix Dashboard
    Spring Cloud 入门教程4、服务容错保护:断路器(Hystrix)
    Spring Cloud 入门教程3、服务消费者(Feign)
    JS==和===总结
    怀疑与批判
    Java多线程速记手册
    编译原理
    C系、Java、JavaScript、C#、PHP、Swift基本语法对比
    单例模式番外篇
  • 原文地址:https://www.cnblogs.com/silentNight/p/5545643.html
Copyright © 2020-2023  润新知