作业--day38

发布时间:2023年12月28日

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();

}

在这里插入图片描述

思维导图

在这里插入图片描述

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