我的c++笔记(2023.2.16)
关于前置递增和后置递增的重载问题
//前置递增
MyInterger& operator++() {
++(this->m_num);
return *this;
}
//后置递增
MyInterger operator++(int) {
MyInterger temp = *this;
this->m_num++;
return temp;
}
区别:前置递增要保持返回值还是当前调用的对象,所以返回的是引用,但是后置递增是返回值类型,因为其返回的是临时的对象,故不能返回引用。而且还是就是后置递增采用的是一个(int)占名来和前置递增产生区别。
总结:前置递增返回引用,后置递增返回值。
关于赋值运算符的重载
class Person{
public:
Person(int age) {
m_age = new int(age);
}
//赋值运算符的重载 编译器自己提供了一种赋值,但那是基于浅复制
Person& operator=(Person& person) {
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
//进行深复制
m_age = new int(*(person.m_age));
return *this;
}
int getage() {
return *m_age;
}
~Person() {
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
}
private:
int* m_age;
};
void test02() {
Person p(18);
Person p1(20);
Person p2(30);
p = p1 = p2;
cout << p.getage() << endl;
cout << p1.getage() << endl;
cout << p2.getage() << endl;
}
这里可以看到结果,并且重新在堆区开辟了空间。