通常如果你使用c part of c++,而且初始化會招致運行期成本,那麼你可以不保證初始化,但是一旦進入c++ no_part of c,那麼你一定要保證對象正確初始化,這就是爲什麼在c中array沒有初始化,但是到了C++中vector卻在對象建立時候調用construtor 初始化,但是我們一定要避免出現C++對象的僞初始化(assigned初始化),下面代碼說明,一下代碼通過VS2008編譯運行
#include <iostream>
#include<fstream>
#include <list>
#include <string>
#ifndef NUL
#define NUL '\0'
#endif
class phone_number
{
public:
phone_number():phone_list("0"){}
phone_number(const std::string& rhs):phone_list(rhs){}
friend std::ostream& operator<<(std::ostream&,const phone_number&);
private:
std::string phone_list;
};
std::ostream& operator<<(std::ostream& out, const phone_number& phone)
{
out<<phone.phone_list;
return out;
}
class man_infor
{
public:
man_infor(const std::string& name,const unsigned int age,const std::string& address, phone_number& phone_)
:the_name(name),the_age(age),the_address(address),the_phone_number(phone_)//推薦初始化方式
{
//the_name = name//這是典型的僞初始化,這樣一方面會增加初始化負荷,另一方面違反C++初始化要在進入構造函數之前完成
}
int show(void)
{
std::cout<<the_name<<"\t"<<the_age<<"\t"<<the_address<<"\t"<<the_phone_number<<std::endl;
return NULL;
}
private:
std::string the_name;
unsigned int the_age;
std::string the_address;
phone_number& the_phone_number;
};
int main ()
{
phone_number mobile_phone("11");
man_infor wang("fish",22,"hfut",mobile_phone);
wang.show();
system("pause");
return NULL;
}