C++ 《运算符重载》
示例代码
#include "iostream" //operator+ using namespace std; class A{ public: int m_age; public: A(){} A(int age):m_age(age){} // A operator+(const A &a){ //成员函数实现重载 // A temp(0); // temp.m_age = m_age+a.m_age; // return temp; // } }; A operator+(const A &a,const A &b){ //全局函数实现重载 A temp(0); temp.m_age = a.m_age+b.m_age; return temp; } A operator+(const A &a,int val){ A temp(0); temp.m_age = a.m_age+val; return temp; } void test1(){ A a1(10); A a2(20); cout<<(a1+a2).m_age<<endl; // 30 cout<<(a1+44).m_age<<endl; // 54 } // operator<< 做一运算符重载(成员函数不能实现) // 一般用于格式化输出 class Person{ public: string m_name; int m_age; public: Person(string name,int age):m_name(name),m_age(age){} }; ostream &operator<<( ostream &out,const Person &p){ out<<"姓名:"<<p.m_name<<"年龄:"<<p.m_age; return out; } void test02(){ Person p("张三",20); cout<<p<<endl; } // 自增重载 class MyInt{ friend ostream &operator<<( ostream &out,const MyInt &p); private: int m_Num; public: MyInt(){ m_Num =0; } //前置++ MyInt &operator++(){ m_Num++; //先++,再返回 return *this; //返回对象本身 } //后置++ MyInt operator++(int ){ MyInt temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++; m_Num++; return temp; } }; ostream &operator<<( ostream &out,const MyInt &p){ out<<p.m_Num; return out; } //赋值运算符重载 class Student{ public: int *m_age; explicit Student(int age){ m_age = new int(age); } Student(const Student &s){ //拷贝函数 m_age = new int(*s.m_age); } ~Student(){ //析构函数 if(m_age != nullptr){ delete m_age; m_age = nullptr; } } //重载赋值运算符 Student &operator=(const Student &s){ if(this == &s){ return *this; } if(m_age != nullptr){ delete m_age; m_age = nullptr; } m_age = new int(*s.m_age); return *this; } //重载相等 bool operator==(Student & stu) const{ if(*m_age == *stu.m_age){ return true; }else{ return false; } } //重载不等运算符 bool operator!=(Student & stu) const{ if(*m_age != *stu.m_age){ return true; } return false; } }; int main(){ test1(); return 0; }
本文来自博客园,作者:一个小笨蛋,转载请注明原文链接:https://www.cnblogs.com/paylove/p/18307688
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!