C++之运算符重载(三)

tech2023-10-18  87

文章目录

一.关系运算符重载二.函数调用运算符重载

一.关系运算符重载

//重载关系("==" "!=" ---(< >) 类比--- )运算符 #include <iostream> #include <string> using namespace std; class Person { private: string m_Name; int m_Age; public: Person(string name,int age){ m_Name = name; m_Age = age; } bool operator==(Person &p){ if(this->m_Name == p.m_Name && this->m_Age == p.m_Age){ return true; }else{ return false; } } bool operator!=(Person &p){ if(this->m_Name == p.m_Name && this->m_Age == p.m_Age){ return false; }else{ return true; } } }; int main(){ Person p1("Tom",1); Person p2("Jack",2); if(p1 == p2){ cout<<"true"<<endl; } if(p1 != p2){ cout<<"false"<<endl; } system("pause"); }

二.函数调用运算符重载

//函数调用运算符(())重载 #include <iostream> #include <string> using namespace std; class Print { public: void operator()(string test){ cout<<test<<endl; } }; class Add { public: void operator()(int a , int b){ cout<<a + b<<endl; } }; void test01(){ Print t; t("hello!"); } void test02(){ Add a; a(100,100); //匿名对象调用 Add() 是一个匿名对象 Add()(100,100); } int main(){ test01(); test02(); }
最新回复(0)