拷备构造和= 赋值的不同在于:拷备构造是在未初始化的内存上进行的操作。= 是在已初始化的内存上进行的操作。
下面的类,将 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, 0x20, sizeof( *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, 0x50, sizeof( *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, 0x20, sizeof( *this ) );
50 assert ( size >=10 );
51 snprintf( this->value, size, "%d", m );
52 this->value[strlen( this->value ) ] = 0x20;
53 }
54
55 };
56
2 struct STR
3 {
4 public:
5 char value[size];
6 public:
7 STR( const char* m )
8 {
9 memset( this, 0x20, sizeof( *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, 0x50, sizeof( *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, 0x20, sizeof( *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, 0x20, sizeof( *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 };
2 {
3 public:
4 SwapData()
5 {
6 memset( this, 0x20, sizeof( *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 };
测试代码: