1.C++四种构造函数:
(1)默认构造函数:这类构造函数没有参数,如定义类Human
class Human {
public :
Human();
private:
int age;
};
Human::Human() {
cout<<"手写的默认构造函数"<<endl;
}
当没写构造函数的时候,编译器自动生成构造函数,实际没有任何效果。
(2)重载构造函数:这类构造函数有参数,例如:
class Human{
public:
Human(); //这是无参默认构造函数
Human(int age,int salary); //这是有参的重载构造函数
private:
int age;
}
Human::Human(int age,int salary) {
this->age = age;
this->salary = salary;
}
(3)拷贝构造函数:当一个已经存在的对象,复制到另一个对象时。
①如果有对象的复制,没有手动写构造函数函数,编译器就自动生成拷贝函数,即浅拷贝;
手动写了就是深拷贝,本来可以写成Human(Human),加const为了保证传入的参不能随意去修改,加&让形参变成引用类型,取个别名就行,不用再形参开辟地址生成新对象,所以写成:
Human(const Human &);
class Human{
public:
Human(); //默认构造
Human(int age); //重载构造
Human(const Human &); //写了就是深拷贝,没写就是编译器自动生成浅拷贝
private:
int age;
};
Human::Human(const Human &other) {
this->age = other.age;
cout<<"深拷贝成功"<<endl;
}
Human h0; //无参默认构造
Human h1(18); //含参重载构造
Human h2 = h1; //深拷贝调用1
Human h3(h1); //深拷贝调用2
注意两点:一定要写成深拷贝,别用系统的浅拷贝,因为当对象有指针类型会出错;
用浅拷贝张三女朋友换成如花,李四女朋友也换到如花。而深拷贝则给李四重新开辟一块内存。
第二点:一个成员函数Human::Compare(Human h1,Human h2)写成这种写法原因
Human & Human::Compare(const Human & h1,const Human &h2),加const为了让函数和形参不能被程序员错误操作修改,总共要生成三次深拷贝(形参两次、返回对象类型一次);加三个引用&为了引用不再生成新对象。
(4)赋值构造函数:
创建了对象之后进行复制对象:
class Human{
public:
Human(); //默认构造
Human(int age); //重载构造
Human(const Human &); //写了就是深拷贝,没写就是编译器自动生成浅拷贝
Human & compare = (const & Human);//重载等于号,赋值构造函数
private:
int age;
};
Human & Human::compare = (const & Human other) {
age = other.age;
return *this;
}
Human h0; //无参默认构造
Human h1(18); //含参重载构造
Human h2 = h1; //深拷贝调用1,这是生成对象的同时
Human h3(h1); //深拷贝调用2
h2 = h1; //调用赋值构造函数,这是生成对象之后
注意区别赋值构造和深拷贝区别:
创建对象的同时并复制时是拷贝构造函数:
h1 = (18);
Human h2 = h1;
创建对象之后再复制是赋值构造函数。
2.析构函数:
(1)定义~Human();系统自动回收空间;不要去写Human::~Human().