• 从一段代码看拷备构造和=赋值的不同


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

    下面的类,将 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 };

    测试代码:

  • 相关阅读:
    iOS 项目中的NSNotification简单使用
    IOS开发之格式化日期时间的使用 && 编程中常见问题
    linker command failed with exit code 1 (use -v to see invocation),经典Xcode编译错误的出现和解决!
    CocoaPods安装和使用教程
    机器学习算法--贝叶斯分类器(二)
    机器学习算法--贝叶斯分类器(一)
    Linux系统初始化过程及运行级别简介
    Linux基本符号
    索引节点inode详解
    Linux文件类型介绍
  • 原文地址:https://www.cnblogs.com/diylab/p/1526983.html
Copyright © 2020-2023  润新知