重载运算符操作_学习
生活随笔
收集整理的這篇文章主要介紹了
重载运算符操作_学习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//A: 操作符重載實現為類成員函數
/*
#include <iostream>
class Person
{
private:int age;
public:Person(int a){this->age=a;}//inline bool operator==(const Person &ps)const;inline bool operator==(const Person *ps)const;
};
//inline bool Person::operator==(const Person &ps)const{
// std::cout<<"this->age=="<<this->age<<", ps.age=="<<ps.age<<"\n";
// if(this->age == ps.age)
// return true;
// else
// return false;
//};
inline bool Person::operator==(const Person *ps)const{std::cout<<"this->age=="<<this->age<<", ps->age=="<<ps->age<<"\n";if(this->age == ps->age)return true;elsereturn false;
};int main()
{//Person p1(10);//Person p2(10);Person *a = new Person(10);Person *b = new Person(10);//if(p1 == p2)if(a == b){std::cout<<"相等\n";}elsestd::cout<<"不相等\n";system("pause");return 0;//由上面的測試可以得出結論,指針與指針之間是不能進行重載運算符比較的
}*///B:操作符重載實現為非類成員函數(全局函數)
#include <iostream>
using namespace std;
class Person
{
public:int age;
};
bool operator==(Person const &p1, Person const &p2)
{if(p1.age == p2.age)return true;elsereturn false;
};class Test
{
private:int m_value;
public:Test(int x=3){ m_value = x; }Test &operator++(); //前增量Test &operator++(int);//后增量void display(){cout<<"m_value="<<m_value<<"\n";}
};//前增量 Test& 是指返回一個Test的地址
Test& Test::operator++(){m_value++; //先增量return *this; //返回當前對像
};//后增量
Test& Test::operator++(int)
{Test tmp(*this); //創建臨時對像m_value++; //再增量return tmp; //返回臨時對像
}int main()
{Person a;Person b;a.age=10;b.age=10;if(a == b){cout<<"相等\n";}elsecout<<"不相等\n";cout<<"進行另外一個測試\n";Test t;t.display();t++;t.display();++t;t.display();system("pause");return 0;
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的重载运算符操作_学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Squid反向代理加速缓存+负载均衡实验
- 下一篇: ObjectiveC 深浅拷贝学习