C++ DAY3 作业

2023-12-28 20:52:52

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

#include <iostream>

using namespace std;

class Person
{
    int *age;
    string &name;  //存在引用成员
public:
    //构造函数
    Person(string name):age(new int),name(name)
    {
        cout << "Person一个参数的有参构造" << endl;
    }
    Person(int age,string name):age(new int(age)),name(name)
    {
        cout << "Person两个参数的有参构造" << endl;
    }
    //析构函数
    ~Person(){
        delete age;
        cout << "Person的析构函数,释放空间:" << age << endl;
    }
    //拷贝构造函数
    Person(const Person&other):age(new int(*(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;
    }
    int get_age();
    string get_name();
};
int Person::get_age()
{
    return *age;
}
string Person::get_name()
{
    return name;
}

class Stu
{
    double *score;
    Person p1;
public:
    //构造函数
    Stu():score(new double),p1(p1)
    {cout << "Stu的无参构造" << endl;}
    Stu(double score):score(new double(score)),p1(p1)
    {cout << "Stu的一个参数有参构造" << endl;}
    Stu(double score,Person p1):score(new double(score)),p1(p1)
    {cout << "Stu的两个参数有参构造" << endl;}
    //析构函数
    ~Stu(){
        delete score;
        cout << "Stu的析构函数,释放空间:" << score << endl;
    }
    //拷贝构造函数
    Stu(const Stu &other):score(new double(*(other.score))),p1(other.p1)
    {
        cout << "Stu的拷贝构造函数" << endl;
    }
    //拷贝赋值函数
    Stu &operator =(const Stu &other)
    {
        *(this->score) = *(other.score);
        this->p1 = other.p1;
        cout << "Stu的拷贝赋值函数" << endl;
        return *this;
    }
    void show(Person p1);
};
void Stu::show(Person p1)
{
    cout << "age:" << p1.get_age() << endl;
    cout << "name:" << p1.get_name() << endl;
    cout << "score:" << *score << endl;
}


int main()
{
    Person p1(18,"zhangsan");
    //Stu s1;
   Stu s2(50);
    s2.show(p1);
//    Person p2("lisi");
//    p2 = p1;
    //Person p2 = p1;

    return 0;
}

2.思维导图

文章来源:https://blog.csdn.net/qq_44121517/article/details/135276768
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。