文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C++高级主题之复制构造函数

C++高级主题之复制构造函数

时间:2011-05-19  来源:COS

复制构造函数

#include<string>
#include<iostream>
using namespace std;

class Department
{
public:
        Department(string _name);
        Department(string _name,char* _address);
        ~Department();
        Department& operator=(const Department& b);
        Department(const Department &b);//复制构造函数
        void print()const;
private:
        string name;
        char* address;
};
Department::Department(string _name)
{
        name=_name;
        address=NULL;
        cout<<"Constructor:";
        print();
}
Department::Department(string _name,char* _address)
{
        name=_name;
        address=new char[strlen(_address)+1];
        strcpy(address,_address);
        cout<<"Constructor:";
        print();
}
Department::~Department()
{
        cout<<"Destructor:";
        print();
        delete []address;
}
Department::Department(const Department& b)
{
        cout<<"复制构造函数:";
        b.print();
        name=b.name;
        if(b.address==NULL)
                address=NULL;
        else
        {
                address=new char[strlen(b.address)+1];
                name=b.name;
                strcpy(address,b.address);
        }
}
Department& Department::operator=(const Department& b)
{
        cout<<"Assignment:";
        print();
        cout<<"= ";
        b.print();
        if(this != &b)
        {
                name=b.name;
                delete[] address;
                if(b.address==NULL)
                    address=NULL;
            else
                {       
                        address=new char[strlen(b.address)+1];
                    name=b.name;
                    strcpy(address,b.address);
                }
        }
    return *this;
}
void Department::print()const
{
        cout<<"name="<<name<<",address=";
        if(address==NULL)
                cout<<"NULL";
        else
                cout<<address;
        cout<<"\n";
}
/*
void fun(Department x)
{
   string p=x.name;//error cannot access private variable
}*/
void main()
{
        Department shipping("shipping");
        Department qc("quality control","china");
        Department dept(qc);
        dept=shipping;
}

程序运行结果:

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载