示例
#include <iostream>
using namespace std;
class Kid
{
private:
int age;
char*name;
char*sex;
public:
Kid(int age,char*name,char*sex);
Kid(const Kid &kid); //自定义拷贝函数
~Kid();
void showKid();
};
Kid::Kid(int age,char*name,char*sex)
{
Kid::age=age;
Kid::name=new char[strlen(name)+1];
strcpy(Kid::name,name);
Kid::sex=new char[strlen(sex)+1];
strcpy(Kid::sex,sex);
}
//Kid::Kid(int age,char *name,char *sex):age(age),name(name),sex(sex) //用成员初始化表对数据成员初始化
//{
//
//}
Kid::Kid(const Kid &kid)
{
Kid::age=kid.age*2;
int c=strlen(kid.name)+1;//一定要+1用来存放‘/0’字符串结束标志,否则会内存溢出
Kid::name=new char[c];
strcpy(Kid::name,kid.name);
Kid::sex=new char[strlen(kid.sex)+1];
strcpy(Kid::sex,kid.sex);
}
Kid::~Kid() //自定义析构函数
{
delete []Kid::name; //delete运算符释放存储空间
delete []Kid::sex;
cout<<"dispose object kid"<<Kid::age<<endl;
}
void Kid::showKid()
{
cout<<"孩子:"<<endl<<"姓名:"<<name<<endl<<"年龄:"<<age<<endl<<"性别:"<<sex<<endl;
}
class Car
{
public:
char*no;
char*brand;
int speed;
void showCar();
~Car();//仿默认析构
};
Car::~Car()
{
cout<<"dispose object car"<<endl;
}
void Car::showCar()
{
cout<<"汽车:"<<endl<<"号码:"<<no<<endl<<"品牌:"<<brand<<endl<<"速度:"<<speed<<"km/h"<<endl;
}
int main()
{
Kid kid(10,"rookie_j","男");
kid.showKid();
cout<<"--------------------"<<endl;
Kid kid2(kid); //代入法调用拷贝构造函数
kid2.showKid();
cout<<"--------------------"<<endl;
Kid kid3=kid2; //赋值法调用拷贝构造函数
kid3.showKid();
cout<<"--------------------"<<endl;
Kid *ptr=new Kid(10,"rookie_x","女"); //使用new运算符动态创建对象
ptr->showKid();
cout<<"--------------------"<<endl;
delete ptr; //释放对象所占的存储空间
Car car={"8888888","Benz",200},car2;//只有没定义构造函数的类,才能用初始值表初始化公有数据成员,默认构造
car.showCar();
cout<<"--------------------"<<endl;
car2=car;//默认拷贝构造函数或car2(car)
car2.showCar();
cout<<"--------------------"<<endl;
return 0;
}
运行结果: