|
发表于 2023-11-10 22:06:13
|
显示全部楼层
本楼为最佳答案
这段代码中存在一些问题。首先是在重载赋值运算符时,应该返回一个指向类的引用。其次,重载赋值运算符函数中缺少返回值。最后,重载赋值运算符函数中应该释放原有内存空间,否则会造成内存泄漏。
以下是修正后的代码:
- #include<iostream>
- #include<cstdio>
- using namespace std;
- class person
- {
- public:
- int *age;
- person(int n)
- {
- age=new int(n);
- }
- ~person()
- {
- if(age!=NULL)
- {
- delete age;
- age=NULL;
- }
- }
- person& operator=(const person& p) // 修正赋值运算符重载函数
- {
- if(this->age!=NULL)
- {
- delete this->age;
- this->age=NULL;
- }
- this->age = new int(*p.age);
- *age = *p.age;
- return *this; // 返回指向类的引用
- }
- };
- ostream& operator<<(ostream& cout, person& p)
- {
- cout<<*p.age;
- return cout;
- }
- void test()
- {
- person p1(18);
- person p2(20);
- cout<<p1<<' '<<p2<<endl;
- p2=p1;
- cout<<p1<<' '<<p2;
- }
- int main()
- {
- test();
- }
复制代码
在修正后的代码中,重载赋值运算符函数返回了指向类的引用,并且在函数中释放了原有内存空间。这样就可以正确输出p1的值为18。 |
|