1. 定义一个Person类,包含私有成员,int *age,string &name,一个Stu类,包含私有成员double *score,Person p1,写出Person类和Stu类的特殊成员函数,并写一个Stu的show函数,显示所有信息。
代码
#include <iostream>using namespace std;class Person
{int *_ptr_age;string &_ref_name;
public://Person constructor,Person(int age, string name):_ptr_age(new int(age)), _ref_name(name){cout << "Person constructor with 2 params" << endl;}//destructor~Person(){cout << "Person destructor" << endl;delete _ptr_age;}//copy constructor. Note: param need to be initilized for spacePerson(const Person &src):_ptr_age(new int(*(src._ptr_age))), _ref_name(src._ref_name){cout << "Person copy constructor" << endl;}//assign constructor. Note it has been initilized, has space alread, just need copy valuePerson &operator=(const Person &src){this->_ptr_age =src._ptr_age;this->_ref_name = src._ref_name;cout << "Person assign constructor" << endl;}int get_age();string get_name();
};class Stu
{double *_ptr_score;Person _person;public://constuctorStu(double score, int age, string name):_ptr_score(new double (score)), _person(age, name){cout << "Stu constructor with 2 params" << endl;}//destructor~Stu(){cout << "Stu destructor" << endl;delete _ptr_score;}//copy constructorStu(const Stu &src):_ptr_score(new double(*(src._ptr_score))), _person(src._person){cout << "Stu copy constructor" << endl;}//assign constructorStu &operator = (const Stu &src){this->_ptr_score = src._ptr_score;this->_person = src._person;}void show();
};int Person::get_age()
{return *_ptr_age;
}string Person::get_name()
{return _ref_name;
}void Stu::show()
{cout << "score = "<< *_ptr_score << endl;cout << "person age = "<< _person.get_age() << endl;cout << "person name = "<< _person.get_name() << endl;}int main()
{int age = 28;string name = "zhangsan";double score = 99;Stu *stu_zs = new Stu(score, age, name);stu_zs->show();delete stu_zs;return 0;
}
第一次写,还是有点搞脑子的😅
运行结果