c++ 赋值运算符重载

Problem Description
一个学生类Student,它有2个数据成员,姓名char* name 、年龄int age。编写这个类的代码。
完善以下程序
//你的代码写在这里
Student::~Student()
{
delete name;
}
int main()
{
Student s1(“czg”, 18), s2;
s2 = s1;
s1.Display();
s2.Display();
return 0;
}
Input Description

Sample Output
czg 18
czg 18

#include <iostream>
using namespace std;
#include <string>
class Student
{
public:
	string * name;
	int * age;
	Student(string a, int b)
	{
		name = new string(a);//将a创建在堆区,并让指针name去维护堆区
		age = new int(b);
	}
	//堆区需要手动释放,即析构函数
	Student()
	{
		//判断不为空,则释放
		if (age != NULL && name != NULL)
		{
			delete age,name;
			age = NULL;
			name = NULL;
		}
	}
	//赋值重载
	Student& operator=(Student &p)
	{
		//编译器提供的重载:name = p.name;  默认浅拷贝
	/*
	* 判断是否有属性在堆区,有先释放干净,再深拷贝
		if (age != NULL && name != NULL)
		{
			delete age, name;
			age = NULL;
			name = NULL;
		}
	*/
		//深拷贝  新在堆区开辟一空间,防止堆区内存重复释放,程序崩溃
		name = new string(*p.name);
		age = new int(*p.age);

		//返回对象本身,连续赋值
		return *this;
	}
	//输出
	void Display()
	{
		cout << *name << " " << *age << endl;
	}
	~Student();
};

Student::~Student()
{
	delete name;
}
int main()
{
	Student s1("czg", 18), s2;
	s2 = s1;
	s1.Display();
	s2.Display();
	return 0;
}
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
class Student
{
public:
    char *name;
    int age;
    Student(const char *a="",int b=0)
    {
        name=new char[strlen(a)+1];
        strcpy(name,a);
        age=b;
    }
    Student& operator=(const Student& s)
    {
        name=new char[strlen(s.name)+1];
        strcpy(name,s.name);
        age=s.age;
    }
    ~Student();
    void Display()
    {
        cout<<name<<" "<<age<<endl;
    }
  
};
Student::~Student()
{
 delete name;
}
int main()
{
 Student s1("czg", 18), s2;
 s2 = s1;
 s1.Display();
 s2.Display();
 return 0;
} 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值