建構子(constructor)
問題討論:
先來看看這個程式:
::::::::::::::::::::::::::::::::::::::::::::::
#include<iostream>
using namespace std;
class People
{
private:
int age;
const int number;
static int total;
public: People(int _age):number(++total) { cout<<"Constructor!!!"<<endl ; age = _age ; } People(const People& _People):number(++total) { cout<<"Copy Constructor!!!"<<endl; age = _People.age; } void Display() { cout<<" Age :" <<age <<" Number:"<<number <<endl; } }; int People::total=0;
void main( ) { People james=20; People tkd(james); james.Display(); tkd.Display(); }
::::::::::::::::::::::::::::::::::::::::::::::
輸出:
Constructor!!!
Copy Constructor!!!
Age :20 Number:1
Age :20 Number:2
這個程式有什麼地方值得注意的呢?我先點出來好了: (1)Copy constructor可以拿掉嗎? (2)可以將在Constructor改為這樣嗎? People(int _age)//:number(++total) { cout<<"Constructor!!!"<<endl ; age = _age ; number = ++total ; } People(const People& _People)//:number(++total) { cout<<"Copy Constructor!!!"<<endl; age = _People.age; number = ++total ; } 有答案了吧!!! (1)Copy constructor拿掉的話,輸出如下: Constructor!!! Age :20 Number:1 Age :20 Number:1 發現問題了吧!!若你沒有撰寫Copy constructor的話,它會呼叫預設的Copy constructor
以memberwise的方式來初始化james:
People tkd(james);
//int age = james.age;
//const int number = james.number;
此時是錯誤的,number的值是由total決定的,所以知道問題所在了吧!!!
(2)Constructor是不能將number(++total)在initialization list改為在body中
為什麼呢?const的變數在初始化後就不能數值指定的方式來做變更,
所以number放在initizlizationlist做初始化的動作,
而不能放在body內做assignment的動作!!!
Written By James On 2004/02/08