- 有以下类定义,写出该类的构造函数,析构函数,拷贝构造函数,要求,所有类对象的空间都是用new动态申请。
class Stu { string name; int age; int score; int *high; };
代码:
#include <iostream>
using namespace std;
class Stu
{
string name;
int age;
int score;
int *high;
public:
Stu()
{
cout << "Stu的无参构造" << endl;
}
Stu(string name, int age, int score, int *high)
{
cout << "Stu的有参构造" << endl;
this->name = name;
this->age = age;
this->score = score;
this->high = high;
}
~Stu()
{
cout << "Stu的析构函数" << endl;
}
Stu (Stu &s):name(s.name), age(s.age), score(s.score)
{
cout << "Stu的拷贝构造函数" << endl;
this->high = new int(*(s.high));
}
void show()
{
cout << "姓名:" << name << " 年龄:" << age << " 成绩:" << score;
cout << " &身高:" << high << " 身高:" << *high << endl;
}
};
int main()
{
int high = 180;
Stu *s1 = new Stu {"张三", 18, 98, &high};
s1->show();
cout << "--------------------------------" << endl;
Stu *s2 = new Stu(*s1);
s2->show();
cout << "--------------------------------" << endl;
delete s1;
delete s2;
return 0;
}
运行结果:
2.思维导图