這是一道十分經典的面試題,可以短時間內考查學生對C++的掌握是否全面,答案要包括C++類的多數知識,保證編寫的String類可以完成賦值、拷貝、定義變量等功能。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#include<iostream> using namespace std; class String { public : String( const char *str=NULL); String( const String &other); ~String( void ); String &operator =( const String &other); private : char *m_data; }; String::String( const char *str) { cout<< "構造函數被調用了" <<endl; if (str==NULL) //避免出現野指針,如String b;如果沒有這句話,就會出現野 //指針 { m_data= new char [1]; *m_data= '' /0 '' ; } else { int length= strlen (str); m_data= new char [length+1]; strcpy (m_data,str); } } String::~String( void ) { delete m_data; cout<< "析構函數被調用了" <<endl; } String::String( const String &other) { cout<< "賦值構造函被調用了" <<endl; int length= strlen (other.m_data); m_data= new char [length+1]; strcpy (m_data,other.m_data); } String &String::operator=( const String &other) { cout<< "賦值函數被調用了" <<endl; if ( this ==&other) //自己拷貝自己就不用拷貝了 return * this ; delete m_data; //刪除被賦值對象中指針變量指向的前一個內存空間,避免 //內存泄漏 int length= strlen (other.m_data); //計算長度 m_data= new char [length+1]; //申請空間 strcpy (m_data,other.m_data); //拷貝 return * this ; } void main() { String b; //調用構造函數 String a( "Hello" ); //調用構造函數 String c( "World" ); //調用構造函數 String d=a; //調用賦值構造函數,因為是在d對象建立的過程中用a來初始化 d=c; //調用重載后的賦值函數 } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/u011421608/article/details/39972425