C++ day3

目录

思维导图

定义一个Person类,包含私有成员,int *age,string &name,一个Stu类,包含私有成员double *score,Person p1,写出Person类和Stu类的特殊成员函数,并写一个Stu的show函数,显示所有信息。


思维导图

定义一个Person类,包含私有成员,int *age,string &name,一个Stu类,包含私有成员double *score,Person p1,写出Person类和Stu类的特殊成员函数,并写一个Stu的show函数,显示所有信息。

#include 

using namespace std;
/*Person类*/
class Person
{
    int *age;
    string &name;
public:

    /*Person有两个参数的构造函数*/
    Person(int a,string &b):age(new int(a)),name(b)
    {
        //        cout << "Person有两个参数的构造函数" << endl;
    }
    /*Person的析构函数*/
    ~Person()
    {
        //     cout << "Person的析构函数" << endl;
        delete age;
    }
    /*Person的拷贝构造函数*/
    Person(const Person &other):age(new int(*(other.age))),name(other.name)
    {
        //        cout << "Person的拷贝构造函数" << endl;
    }
    /*Person的拷贝赋值函数*/
    Person &operator=(const Person &other)
    {
        *(this->age)=*(other.age);
        this->name=other.name;
        //         cout << "Person的拷贝赋值函数" << endl;
        return *this;
    }
    int get_age(); //获取age
    string get_name(); //获取name
};
/*Stu类*/
class Stu
{
    double *score;
    Person p1;
public:
    /*Stu有两个参数的构造函数*/
    Stu(double a,Person b):score(new double(a)),p1(b)
    {
        //        cout << "Stu有两个参数的构造函数" << endl;
    }
    /*Stu的析构函数*/
    ~Stu()
    {
        //        cout << "Stu的析构函数" << endl;
        delete score;
    }
    /*Stu的拷贝构造函数*/
    Stu(const Stu &other):score(new double(*(other.score))),p1(other.p1)
    {
        //        cout << "Stu的拷贝构造函数" << endl;
    }
    /*Stu的拷贝赋值函数*/
    Stu &operator=(const Stu &other)
    {
        *(this->score)=*(other.score);
        this->p1=other.p1;
        //         cout << "Stu的拷贝赋值函数" << endl;
        return *this;
    }
    void show(); //查看所有信息
};
/*获取age*/
int Person::get_age()
{
    return *age;
}
/*获取name*/
string Person::get_name()
{
    return name;
}
/*显示所有信息*/
void Stu::show()
{
    cout << "name="  << p1.get_name() << endl;
    cout << "age="  << p1.get_age() << endl;
    cout << "score=" << *score << endl;
}
/***********************主函数**************************/
int main()
{

    string n="zhangsan";
    Person p1(20,n);
    Stu s1(80,p1);

    string n2="lisi";
    Person p2(18,n2);
    Stu s2(90,p2);
    s2.show();
    s2=s1;
    s2.show();


    return 0;
}

C++ day3_第1张图片

你可能感兴趣的:(c++,开发语言)