C++作业3

设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。

代码:

cpp 复制代码
#include <iostream>

using namespace std;

class Per
{
private:
    string name;
    int age;
    double *height;
    double *weight;
public:
    Per()
    {
        cout << "per无参" << endl;
    }

    Per(string name,int age,double height,double weight):name(name),age(age),height(new double(height)),weight(new double(weight))
    {
        cout << "per有参" << endl;
    }

    Per(const Per &other):name(other.name),age(other.age),height(new double(*(other.height))),weight(new double(*(other.weight)))
    {
        cout << "per拷贝" << endl;
    }

    ~Per()
    {
        delete height;
        delete height;
        height = nullptr;
        weight = nullptr;
        cout << "per析构" << endl;
    }

    void show();

};

void Per::show()
{
    cout << "name:" << name << endl;
    cout << "age:" << age << endl;
    cout << "height:" << *height << endl;
    cout << "weight:" << *weight << endl;
}

class Stu
{
private:
    double score;
    Per p1;
public:
    Stu()
    {
       cout << "stu无参" << endl;
    }

    Stu(double score,string name,int age,double height,double weight):score(score),p1(name,age,height,weight)
    {
        cout << "stu有参" << endl;
    }

    Stu(const Stu &other):score(other.score),p1(other.p1)
    {
        cout << "stu拷贝" << endl;
    }

    ~Stu()
    {
        cout << "stu析构" << endl;
    }

    void show();
};

void Stu::show()
{
    cout << "score:" << score << endl;
    p1.show();
}

int main()
{
    Per s1("张三",18,1.7,120);
    s1.show();
    cout << "-----------------------" << endl;
    Per s2(s1);
    s2.show();
    cout << "-----------------------" << endl;
    Stu s3(98,"李四",21,1.8,125);
    s3.show();
    cout << "-----------------------" << endl;
    Stu s4(s3);
    s4.show();
    return 0;
}

运行结果:

思维导图:

相关推荐
zhangyao9403301 小时前
关于js导入Excel时,Excel的(年/月/日)日期是五位数字的问题。以及对Excel日期存在的错误的分析和处理。
开发语言·javascript·excel
骑驴看星星a1 小时前
【Three.js--manual script】4.光照
android·开发语言·javascript
2301_795167202 小时前
玩转Rust高级应用 如何避免对空指针做“解引用”操作,在C/C++ 里面就是未定义行为
c语言·c++·rust
星释2 小时前
Rust 练习册 :Leap与日期计算
开发语言·后端·rust
悟能不能悟4 小时前
java的java.sql.Date和java.util.Date的区别,应该怎么使用
java·开发语言
循环过三天4 小时前
3.4、Python-集合
开发语言·笔记·python·学习·算法
_院长大人_6 小时前
设计模式-工厂模式
java·开发语言·设计模式
MATLAB代码顾问6 小时前
MATLAB实现决策树数值预测
开发语言·决策树·matlab
不染尘.7 小时前
2025_11_7_刷题
开发语言·c++·vscode·算法
似水এ᭄往昔7 小时前
【C++】--stack和queue
开发语言·c++