【C++】类中有指针类型的成员变量

如果一个类中有指针类型的成员变量,就要在构造函数中new动态分配内存,也需要在析构函数中delete释放内存

视频:学习通C++的2.6.2节

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class Student {
public:
    Student(const char* s, int aa);
    void SetName(const char* s);  //修改名字
    void Show();  //打印名字和年龄
    ~Student();
private:
    char* name;
    int age;
};

int main()
{
    Student s1("Bob", 20);  //程序里一共有两个Bob,栈中有一个Bob,堆中还有一个Bob,因为类中拷贝了一次Bob到堆里
    Student* s2 = new Student("Klieam", 20);

    s1.Show();
    s2->Show();
    s1.SetName("李四");
    s2->SetName("张三");
    cout << "修改后" << endl;
    s1.Show();
    s2->Show();

    delete s2;  //调用析构函数,释放Klieam
    return 0;
}              //main函数结束后才调用析构函数,释放Bob  

Student::Student(const char* s, int aa):age(aa)
{
    name = new char[strlen(s) + 1];  //成员变量是指针,所以应该用new来分配内存,+1是因为有结束标志符
    strcpy(name, s);
}

void Student::SetName(const char* s)
{
    delete[] name;  //释放旧名字
    name = new char[strlen(s) + 1];  //重新分配内存,因为新名字可能比旧名字长,也可能比旧名字短
    strcpy(name, s);
}

void Student::Show()
{
    cout << name << ":" << age << "岁" << endl;
}

Student::~Student()
{
    delete[] name;
}

  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值