2012-08-30 39 views
1

我的代碼也可以找到here如何正確地從內部運算符構造函數調用複製構造函數?

此代碼將工作(但仍然有很多重複代碼):

Employee::Employee(const Employee& x) 
{ 
     name=new char [strlen(x.name)+1]; 
     strcpy(name, x. name); 
     strcpy(EGN, x.EGN); 
     salary=x.salary; 
} 

void Employee::operator=(const Employee& x) 
{ 
     delete[] name; 
     name=new char [strlen(x.name)+1]; 
     strcpy(name, x. name); 
     strcpy(EGN, x.EGN); 
     salary=x.salary; 
} 

Employee::Employee(char* n, char* e, double s) 
{ 
     name = new char [strlen(n)+1]; 
     strcpy(name, n); 
     strcpy(EGN, e); 
     salary=s; 
} 

下面是我試圖避免編寫同樣的事情三次...但它不工作。難道不能縮短代碼嗎?

Employee::Employee(char* n, char* e, double s) 
{ 
     name = new char [strlen(n)+1]; 
     strcpy(name, n); 
     strcpy(EGN, e); 
     salary=s; 
} 

Employee::Employee(const Employee& x) 
{ 
     Employee(x.name, x.EGN, x.salary); 
} 

void Employee::operator=(const Employee& x) 
{ 
     delete[] name; 
     Employee(x); 
} 
+2

請將代碼添加到您的文章,而不是外部網站。 –

+1

將'name'聲明爲'std :: string',讓編譯器爲你生成三巨頭並繼續前進。 – jrok

+0

不可以,它必須是char * –

回答

4

您不能調用構造函數作爲成員函數。你可以創建一個成員函數,並從構造函數和所有其他地方調用它。

void Employee::Init(const char* n, const char* e, double s) 
{ 
     name = new char [strlen(n)+1]; 
     strcpy(name, n); 
     strcpy(EGN, e); 
     salary=s; 
} 

void Employee::Init(const Employee &x) 
{ 
     Init(x.name, x.EGN, x.salary); 
} 

Employee::Employee(char* n, char* e, double s) 
{ 
    Init(n,e,s); 
} 


Employee::Employee(const Employee& x) 
{ 
    Init(x); 
} 

void Employee::operator=(const Employee& x) 
{ 
     delete[] name; 
     Init(x); 
} 
+0

C++ 11不允許構造函數鏈接嗎? –

+0

@Loki,OP沒有詢問構造函數鏈,如果我理解正確,他想從他的類的不同地方調用構造函數(特別是'operator =')。我錯了嗎?回答你 - 當然它允許。 – littleadv

+0

好的還有一個問題 - 如果EGN是char [10],而不是char *,那麼你會如何完成這項工作? –

6

你正在嘗試的是不被該語言允許的。然而,C++ 11允許delegating constructors,所以你可以做這樣的事情:

Employee::Employee(const Employee& x) : Employee(x.name, x.EGN, x.salary){} 

注意,一個構造函數在其他的初始化列表。

在C++ 11之前,一個選項可能會有一些從所有構造函數中調用的初始化函數。然而,這在語義上是不同的,因爲函數調用執行賦值給成員變量,而不是初始化。

1

嘗試在C++ 11

Employee::Employee(char* n, char* e, double s) 
{ 
     name = new char [strlen(n)+1]; 
     strcpy(name, n); 
     strcpy(EGN, e); 
     salary=s; 
} 

// Constructor chaining (delegation) like this. 
Employee::Employee(const Employee& x) 
    : Employee(x.name, x.EGN, x.salary) 
{} 


// Use copy and swap for the assignment operator: 

// Common convention to return a reference to yourself to allow chaingin. 
Employee& Employee::operator=(Employee x) // Pass by value to get the copy. 
{ 
    x.swap(*this);       // Then swap members 
    return *this; 
}           // Destructor will then cleanup.