如果一个类中有指针类型的成员变量,就要在构造函数中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;
}