1.定义一个Person类,包含私有成员,int *age,string &name,一个Stu类,包含私有成员double *score,Person p1,写出Person类和Stu类的特殊成员函数,并写一个Stu的show函数,显示所有信息。
#include <iostream>
#include <iomanip>
using namespace std;
class Person{
private:
int *age;
string &name;
public:
Person(int age, string &name):age(new int(age)),name(name){
cout << "调用Person构造函数" << endl;
}
Person(const Person &other):age(new int(*(other.age))), name(other.name){
cout << "调用Person拷贝构造函数" << endl;
}
Person &operator=(const Person &other){
*age = *(other.age);
cout << "调用Person拷贝赋值函数" << endl;
return *this;
}
~Person(){
delete age;
cout << "调用Person析构函数" << endl;
}
int get_age();
string get_name();
};
int Person::get_age(){
return *age;
}
string Person::get_name(){
return name;
}
class Stu{
private:
double *score;
Person p1;
public:
Stu(double score, int age, string &name):score(new double(score)), p1(age,name){
cout << "调用Stu构造函数" << endl;
}
Stu(const Stu &other):score(new double(*(other.score))), p1(other.p1){
cout << "调用Stu拷贝构造函数" << endl;
}
Stu &operator=(const Stu &other){
*score = *(other.score);
p1 = other.p1;
cout << "调用Stu拷贝赋值函数" << endl;
return *this;
}
~Stu(){
delete score;
cout << "调用Stu析构函数" << endl;
}
void show();
};
void Stu::show(){
cout << "score = " << *score << " age = " << p1.get_age() << " name = " << p1.get_name() << endl;
}
int main(){
string name = "张三";
Stu a(78.4, 18, name);
a.show();
}
思维导图