C++day3——类中的成员函数

思维导图:

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

#include <iostream>

using namespace std;
class Per
{
private:
    string name;
    int age;
    double *height;
    double *weight;
public:
    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()
    {
        delete height;
        delete 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;
    }
    void show()
    {
        cout << "name:" << name <<endl;
        cout << "age:" << age <<endl;
        cout << "height:" << *height <<endl;
        cout << "weight:" << *weight <<endl;
     }
};
class Stu
{
private:
    int score;
    Per p1;
public:
    Stu(int score,string name,int age,double height,double weight):score(score),p1(name,age,height,weight)
    {
        cout << "Stu::有参构造函数" << endl;
    }
    ~Stu()
    {
        cout << "Stu::析构函数" << endl;
    }
    Stu(const Stu &other):score(other.score),p1(other.p1)
    {
        cout << "Stu::拷贝构造函数" << endl;
    }
    void show()
    {
        p1.show();
        cout << "score:" << score <<endl;

     }
};





int main()
{
    Stu s1(88,"张三",18,175.3,160.2);
    s1.show();
    Stu s2(s1);
    s2.show();
    return 0;
}


 

相关推荐

  1. 【C++ 】成员函数和析构函数作用

    2024-03-14 07:56:01       23 阅读
  2. 与对象():6个默认成员函数

    2024-03-14 07:56:01       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-14 07:56:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-14 07:56:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-14 07:56:01       82 阅读
  4. Python语言-面向对象

    2024-03-14 07:56:01       91 阅读

热门阅读

  1. 浏览器文件下载

    2024-03-14 07:56:01       40 阅读
  2. IO进程线程day8

    2024-03-14 07:56:01       33 阅读
  3. 你知道数据库有哪些约束吗?

    2024-03-14 07:56:01       41 阅读
  4. Ribbon跟Nginx实现负载均衡的区别!

    2024-03-14 07:56:01       41 阅读
  5. 【分布式websocket】聊天系统消息加密如何做

    2024-03-14 07:56:01       48 阅读
  6. 基于左逆的三点法测距,MATLAB函数

    2024-03-14 07:56:01       35 阅读
  7. 【MATLAB】界面是两个连续的GUI时如何调出第二个

    2024-03-14 07:56:01       46 阅读
  8. Oracle 10g字符编码

    2024-03-14 07:56:01       40 阅读
  9. MERGE Into 的用法在ORACLE和高斯数据库上的差异

    2024-03-14 07:56:01       32 阅读