示例代码
#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;
}
标签:const,temp,int,age,C++,运算符,operator,重载
From: https://www.cnblogs.com/paylove/p/18307688