zoukankan      html  css  js  c++  java
  • 从一段代码看拷备构造和=赋值的不同

    拷备构造和= 赋值的不同在于:拷备构造是在未初始化的内存上进行的操作。= 是在已初始化的内存上进行的操作。

    下面的类,将 int 和 char*类型的数据都转为 char[]。转换后的字符左对齐,右边空白处用空格填充。

     1 template< int size >
     2 struct STR 
     3 {
     4 public:
     5     char value[size];
     6 public:
     7     STR( const char* m )
     8     {
     9         memset( this,  0x20sizeof*this ) );
    10         // 缓冲溢出检查
    11         if ( strlen( m ) >= size  )
    12         {
    13             throw"too long arguement" );
    14         }
    15         strncpy( this->value, m, size );
    16         this->value[strlen( m )] = 0x20;        
    17     }
    18     STR(  )
    19     {
    20         memset( this,  0x50sizeof*this ) );
    21     }
    22     ~STR(  )
    23     {
    24     
    25     }
    26     STR& operator = (  const char* m   )
    27     {
    28         // 缓冲溢出检查
    29         if ( strlen( m ) >= size  )
    30         {
    31             throw"too long arguement" );
    32         }
    33         strncpy( this->value, m, size );
    34         // pad with write space
    35         memset( &this->value[strlen( m )], 0x20, size - strlen( m ) );
    36         return *this;
    37         
    38     }
    39 
    40     STR& operator = ( int m   )
    41     {
    42         assert ( size >=10 );
    43         snprintf( this->value, size, "%d", m );
    44         this->value[strlen( this->value ) ] = 0x20;
    45         return *this;
    46     }
    47     STR( int m )
    48     {
    49         memset( this,  0x20sizeof*this ) );
    50         assert ( size >=10 );
    51         snprintf( this->value, size, "%d", m );
    52         this->value[strlen( this->value ) ] = 0x20;        
    53     }
    54 
    55 };
    56 


    下面的类使用了上面的代码:

     1 class SwapData
     2 {
     3 public:
     4     SwapData()
     5     {
     6         memset( this,  0x20sizeof*this ) );
     7     }
     8     ~SwapData()
     9     {
    10         
    11     }
    12 public:
    13     STR<12> m_nBillNum;
    14     STR<12> m_lItemLeft;
    15     STR<10> m_lItemTop;
    16 };

    测试代码:

  • 相关阅读:
    决策树(chap3)Machine Learning In Action学习笔记
    AdaBoost-Machine Learning In Action学习笔记
    支持向量机-Machine Learning In Action学习笔记
    Alamofire 4.0 迁移指南
    从VSS到SVN再到Git 记Git的基本操作
    倍杀测量者
    P3166 数三角形
    APIO2014 序列分割(斜率优化好题)
    P3694 邦邦的大合唱站队
    ACwing 298 栅栏(单调队列DP)
  • 原文地址:https://www.cnblogs.com/diylab/p/1526983.html
Copyright © 2011-2022 走看看