c++保证对象在创建时正确初始化

来源:互联网 发布:破解苹果id软件 编辑:程序博客网 时间:2024/06/15 03:03

通常如果你使用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;
}