|
我写的运算符重载代码好像没有调用,但是看不出问题在哪
Cstu& Cstu::operator=(Cstu& lisi) { //重载+号的实现
this->num = lisi.num;
this->age = lisi.age;
this->sex = lisi.sex;
if (name_char) {
delete[] name_char;
name_char = NULL;
}
int len_c = strlen(lisi.name_char)+1;
this->name_char = new char[len_c];
strcpy(this->name_char, lisi.name_char);
cout << "性别:" << this->sex << endl;
return *this;
}
Cstu::Cstu(const char* name, char sex, int num, int age) {
this->name = (char*)name;
this->sex = sex;
this->num = num;
this->age = age;
}
复制代码
下面是声明:
#pragma once
#include <iostream>
using namespace std;
class Cstu
{
public:
char* name;
char sex;
int age;
int num;
Cstu() {};
~Cstu();
Cstu(const char* name, char sex, int num, int age);
Cstu& operator=(Cstu& lisi);
};
复制代码
下面是调用:
void test() {
Cstu stu_zhangsan("张三", 'g', 12, 2345);
Cstu stu_fuzhi = stu_zhangsan;
}
好像没有调用运算符重载,我在重载里面下断点,没有断下来
这个是测试通过的重载=
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
m_Age = new int(age);
}
int* m_Age;
~Person()
{
if(m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
Person& operator=(Person& p)
{
if(m_Age != NULL)
{
//如果已经在堆区分配内存,先释放
delete m_Age;
m_Age = NULL;
}
//将赋值的对象,深拷贝给被赋值对象
m_Age = new int(*p.m_Age);
return *this;
}
};
void test01()
{
Person p1(18);
cout << "p1 age: " << *p1.m_Age << endl;
cout << "------------" << endl;
Person p2(20);
cout << "p2 age: " << *p2.m_Age << endl;
/*需要重载=,进行深拷贝,防止p2,p1中m_Age都保存了同一块内存地址
* 在p2调用析构函数释放了m_Age中的内存后,p1调用析构函数释放同一块内存
* */
p2 = p1;
cout << "p1 age: " << *p1.m_Age << endl;
cout << "p2 age: " << *p2.m_Age << endl;
cout << "------------" << endl;
Person p3(30);
cout << "p3 age: " << *p3.m_Age << endl;
p3 = p2 = p1;//连等号赋值
cout << "p1 age: " << *p1.m_Age << endl;
cout << "p2 age: " << *p2.m_Age << endl;
cout << "p3 age: " << *p3.m_Age << endl;
}
int main(void)
{
test01();
return 0;
}
|
上一篇: socket 通讯接收不到数据下一篇: GetCheckedRadioButton 获取 Radio 组选中状态时,提示未定义标识符
|