- 定义一个Person类,私有成员int age,string &name,定义一个Stu类,包含私有成员double *score,写出两个类的构造函数、析构函数、拷贝构造和拷贝赋值函数,完成对Person的运算符重载(算术运算符、条件运算符、逻辑运算符、自增自减运算符、插入/提取运算符)
#include <iostream>
using namespace std;
// 2.定义一个Person类,私有成员int age,string &name,定义一个Stu类,包含私有成员double *score,
// 写出两个类的构造函数、析构函数、拷贝构造和拷贝赋值函数,完成对Person的运算符重载(算术运算符、
// 条件运算符、逻辑运算符、自增自减运算符、插入/提取运算符)
class Person{
int age;
string &name;
public:
Person(string &name):age(0),name(name){}
Person(int age,string &name):age(age),name(name){}
//拷贝构造函数
Person(const Person &other):age(other.age),name(other.name){
cout << "person 拷贝构造函数" << endl;
}
//拷贝赋值函数
Person &operator=(const Person &other){
this->age = other.age;
this->name = other.name;
cout << "person 拷贝赋值函数" << endl;
return *this;
}
//算术运算符
friend Person operator+(Person &c1,Person &c2);
//条件运算符
friend bool operator==(Person &c1,Person &c2);
//逻辑运算符
friend bool operator&&(Person &c1,Person &c2);
//自增自减运算符(后自加)
Person operator++(int);
//插入/提取运算符
friend ostream &operator<<(ostream &out,Person &c1);
void show();
};
void Person::show(){
cout << "person age = " << age << endl;
cout << "person name = " << name << endl;
}
ostream &operator<<(ostream &out,Person &c1){
out << "age = " << c1.age << " name = " << c1.name;
return out;
}
Person Person::operator++(int){
string str ="";
Person temp(str);
temp.age = this->age++;
return temp;
}
Person operator+(Person &c1,Person &c2){
string str ="";
Person temp(str);
temp.age = c1.age + c2.age;
return temp;
}
bool operator==(Person &c1,Person &c2){
return c1.age == c2.age;
}
class Stu{
double *score;
public:
//构造函数
Stu(double score):score(new double(score)){}
//析构函数
~Stu(){
delete score;
}
//拷贝构造函数
Stu(const Stu &other):score(other.score){
cout << "stu 拷贝构造函数" << endl;
}
//拷贝赋值函数
Stu &operator=(const Stu &other){
*(this->score) = *(other.score);
cout << "stu 拷贝构造函数" << endl;
return *this;
}
};
int main()
{
string name ="张三";
Person per(20,name);
//调用构造函数
Person per2 = per;
per2.show();
cout <<"-----------------------------------------------------" << endl;
string name1 ="ww";
Person per3(name1);
//调用构造函数
per3 = per2;
per3.show();
cout <<"-----------------------------------------------------" << endl;
Person per4 = per2+per3;
per4.show();
bool res = per2 == per3;
cout << "per2 == per3 结果 = " << res << endl;
cout <<"-----------------------------------------------------" << endl;
cout << per << endl;
return 0;
}
2. 思维导图