1.构造函数一般方式
2.初始化列表方式,构造函数
3.委托构造函数
4.析构函数
5.浅拷贝
6.深拷贝
7.移动构造
#include <iostream>
#include <string>
using namespace std;
class stu{
public:
string name;
int age;
stu(){
cout << "无参构造"<< endl;
}
stu(string name){
cout << "有参构造1"<< endl;
}
stu(string name,int age){
cout << "有参构造2"<< endl;
}
};
class teacher{
public:
string name;
int age;
teacher(string name,int age):name(name),age(age){
cout << "有参构造"<< endl;
}
};
class school{
public:
string name;
int age;
school():name{"希望小学"},age(30){
};
school(string name):school{name,100}{
};
school(string name,int age):name{name},age{age}{
};
};
class stu2{
public:
string name;
int age;
stu2(string name,int age){
cout << "有参构造"<< endl;
}
~stu2(){
cout << "析构函数"<< endl;
}
};
class stu3{
public:
string name;
int age;
stu3(string name,int age):name(name),age(age){
cout << "有参构造"<< endl;
}
stu3(const stu3 & s){
cout << "调用拷贝构造```"<< endl;
name = s.name;
age = s.age;
}
~stu3(){
cout <<"析构函数"<< endl;
}
};
class hospital{
public:
string name;
string *address;
hospital(string name,string *address):name(name),address(address){
cout << "拷贝构造"<< endl;
}
hospital(const hospital & h){
cout << "调用拷贝构造"<< endl;
name = h.name;
if(address== nullptr){
address = new string;
address = h.address;
}
}
~hospital(){
cout << "调用析构函数"<<endl;
if(address != nullptr){
address = nullptr;
}
}
};
class lecturer{
public:
string *name;
lecturer():name(new string("豆花")){
cout << "执行构造函数lecturer"<<endl;
}
lecturer(const lecturer &le):name(new string(*le.name)){
cout << "拷贝构造函数~"<<endl;
}
lecturer(lecturer && lec):name(lec.name){
cout << "移动构造lec"<<endl;
lec.name = nullptr;
}
~lecturer(){
cout << "析构函数lecture"<< endl;
delete name;
}
};
lecturer getLec(){
lecturer ll;
return ll;
}
int main() {
stu s;
stu s2("小明");
stu s3("小红",18);
teacher t("王老师",38);
school sc;
school sc2("豆花");
stu2 * s21 = new stu2("小明",18);
delete s21;
stu3 s31("小丽",12);
stu3 s32 = s31;
cout << s32.name << s32.age << endl;
string address = "北京路";
hospital h1("协和医院",&address);
hospital h2 = h1;
*h1.address = "上海路";
lecturer ll = getLec();
return 0;
}