C++:论类的重载运算符

版权声明:K5出品,必属精品,欢迎收藏评论 https://blog.csdn.net/a694861283/article/details/90204956

一、重载运算符

1.用处

重载运算符用于两个类对象进行操作,而一般的运算符都是对类变量进行操作

2.使用重载运算符

//1.声明
class person{
 
private:
    int age;
 
public:
    person(int a){
        this->age=a;
    }
 
    inline bool operator == (const person &ps) const;
};
 
 
//2.定义
bool person::operator== (const person &ps) const{
    
    if(this->age==ps.age){
        return true;
    }
 
    return false;
}
 
//3.调用
int main(){
    person p1(10);
    person p2(20);
 
    if(p1==p2){
        ...
    }
}
//全局重载运算符,没有this指针
bool operator== (person& p1,person const& p2){
    
    if(p1.age==p2.age){
        return true;
    }
 
    return false;
}

猜你喜欢

转载自blog.csdn.net/a694861283/article/details/90204956