#include <iostream>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(const char* name, int age) :name(name), age(age) {}
/*这里>,<,-运算符函数为全局的函数,类里的声明为friend,因为
Person的成员变量为private,在全局的函数里要访问私有成员变量,则
要声明为友元函数*/
friend bool operator<(const Person& b1, const Person& b2);
friend bool operator>(const Person& b1, const Person& b2);
friend bool operator-(Person& t1, Person& t2);
bool operator+(Person& t1);
bool operator=(const Person& b1);
};
bool operator-(Person& t1, Person& t2)
{
//...
return true;
}
bool operator<(const Person& b1, const Person& b2)
{
//...
return true;
}
bool operator>(const Person& b1, const Person& b2)
{
//...
return true;
}
/*重载运算符,+,=这里是成员函数的类外定义,
左操作数为this*/
bool Person::operator=(const Person& b1)
{
//..
}
bool Person::operator+(Person& t1)
{
//...
}
int main()
{
Person ob1("a",1);
Person ob2("a", 2);
if (ob1 < ob2)
{
std::cout << "666" << std::endl;
}
system("pause");
}
运算符重载定义与声明的两种方式。
最新推荐文章于 2022-09-18 22:17:30 发布