C++ day3 (类的构造函数重载)

文章展示了如何在C++中为一个包含动态分配内存的类(Stu)编写构造函数、析构函数和拷贝构造函数。构造函数初始化一个长度为10的字符串并动态分配内存,析构函数负责释放内存。拷贝构造函数处理对象复制时的内存深拷贝问题。
摘要由CSDN通过智能技术生成

 

 

 作业:

  1. 有以下类定义,写出该类的构造函数,析构函数,拷贝构造函数,要求,构造函数要创建出长度为10的字符串给name用,所有类对象的空间都是用new动态申请。

class Stu {

string name;

int age; i

nt score;

int *high;

};

#include <iostream>
#include <cstring>
using namespace std;

class Stu
{
public:
    string name;
    int age;
    int score;
    int *high;
public:
    //无参构造
    Stu ()
    {
        
        //  int *my_score = &this->score; 
        //  my_score=new int;
        
        this->high = new int;
        this->name = new char[10];
        cout << "无参构造" << endl;
    }
    //析构函数
    ~Stu()
    {
        cout << "调用析构函数" << endl;
        delete high;
        delete &name;

    }
    //拷贝函数
    Stu (Stu &a):name(a.name),age(a.age),score(a.score)
    {
        cout << "调用拷贝函数" << endl;
        this->high = new int;
        memcpy(this->high,a.high,sizeof(*(a.high)));
    }
    void show();
  };

void Stu::show()
{
    cout << "姓名 :" << name << endl;
    cout << "年龄 :" << age << endl;
    cout << "分数 :" << score << endl;
    cout << "身高 :" << *high << endl;

}

int main()
{
    cout << "Hello World!" << endl;
    Stu student1;
    student1.age=18;
    *student1.high=178;
    student1.name="小明";
    student1.score=98;
    student1.show();
    Stu student2=student1;
    student2.show();

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值