析构函数报错

博客探讨了在C++中,当析构函数尝试删除指向常量的指针时,为何会导致程序中断。问题源于析构函数中误用`delete addr`操作,而addr初始指向"China"这个常量字符串。正确的做法是将addr初始值设为NULL,并在构造函数中为指针成员分配内存,以避免对常量区域的非法释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标准代码(正确代码)

#include <iostream>
#include <Windows.h>
//#include <string>
#include "Human.h"
using namespace std;

#define addr_len  64
//定义一个"人类"

class Human {
public:
	Human();
	Human(const Human &);
	Human(int age, int salary, string name);
	Human& operator=(const Human &other);
	~Human();
	void description() const;
	string getName() const;
	int getAge() const;
	int getSalary();
	void setAddr(char*addr);
private:
	int age = 22;
	int salary = 25000;
	string name = "无名氏";
	char *addr = "china";

};


Human::Human(const Human &other) {
	name = other.name;
	age = other.age;
	salary = other.salary;
	cout << "调用手动拷贝函数" << endl;
}
Human::~Human() {
	delete addr;
}
string Human::getName() const {
	return name;
}
int Human::getAge() const {
	return age;
}
int Human::getSalary() {
	return salary;
}
void Human::description() cons
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值