C++之运算符重载(二)

tech2023-08-01  93

文章目录

一 . "++"(自增)运算符重载二 . "="(赋值)运算符重载

一 . “++”(自增)运算符重载

//重载++(自增)运算符 #include <iostream> using namespace std; class MyInteger { friend ostream & operator<<(ostream &cout , MyInteger myint); private: int m_Num; public: MyInteger() { m_Num = 0; } //重载前置运算符 MyInteger& operator++(){ m_Num++; return *this; } //重载后置运算符(占位参数int表示重载后置递增) MyInteger operator++(int){ //先保留原来数据 // MyInteger temp; // temp.m_Num = this->m_Num; MyInteger temp = *this; //再递增 m_Num++; return temp; } }; //重载<<运算符 ostream & operator<<(ostream &cout , MyInteger myint){ cout<<myint.m_Num; return cout; } //测试前置递增 void test01(){ MyInteger int01; cout<<"测试前置递增"<<endl; cout<<++int01<<endl; cout<<int01<<endl; } //测试后置递增 void test02(){ MyInteger int02; cout<<"测试后置递增"<<endl; cout<<int02++<<endl; cout<<int02<<endl; } int main(){ test01(); test02(); system("pause"); }

二 . “=”(赋值)运算符重载

//重载=(赋值)运算符 //为什么要重载= //答 : 编译器提供的赋值运算符重载,默认提供的是一个浅拷贝的操作,如果有一些数据属性创建在堆区,会出现问题,当析构函数中执行delete操作时,会造成堆区内存重复释放 #include <iostream> using namespace std; class Book { private: int *m_Num; public: Book(int num){ m_Num = new int(num); } ~Book(){ if(m_Num != NULL){ delete m_Num; m_Num = NULL; } } void showNum(){ cout<<*m_Num<<endl; } //重载= Book& operator=(Book &book){ //因为编译器提供的赋值操作是浅拷贝 m_Num = book.m_Num; 会造成堆区内存重复释放 //先判断它的堆区是否占有内存,清空 if(m_Num != NULL){ delete m_Num; m_Num = NULL; } //开辟新的内存存放原数据属性 m_Num = new int(*book.m_Num); return *this; } }; int main(){ Book b1(1); Book b2(2); Book b3(3); cout<<"赋值前"<<endl; b1.showNum(); b2.showNum(); b3.showNum(); b3 = b2 = b1; cout<<"赋值后"<<endl; b1.showNum(); b2.showNum(); b3.showNum(); }
最新回复(0)