- 加号 + :
Person operator+(Person p);
#include
using namespace std;
class Person
{
public:
Person(int a, int b): m_A(a), m_B(b)
{
}
int m_A;
int m_B;
Person operator+(Person p)
{
Person temp(0, 0);
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
};
};
int main()
{
Person p1(10, 20);
Person p2(10, 20);
Person p3 = p1 + p2;
}
- 左移运算符 << :
ostream & operator<<(ostream &cout, Person p);
#include
using namespace std;
class Person
{
friend ostream &operator<<(ostream &cout, Person p);
public:
Person(int a, int b): m_A(a), m_B(b)
{
}
int m_A;
int m_B;
};
ostream & operator<<(ostream &cout, Person p)
{
cout << " m_A = " << p.m_A << " m_B = " << p.m_B << endl;
return cout;
}
int main()
{
Person p(10, 20);
cout << p << endl;
}
- 递增运算符 ++ :
Person & operator++()
, Person operator++(int)
#include
using namespace std;
class Person
{
public:
Person(int a, int b): m_A(a), m_B(b)
{
}
Person & operator++()
{
this->m_A++;
return *this;
}
Person operator++(int)
{
Person temp = *this;
this->m_A++;
return temp;
}
int m_A;
int m_B;
};
ostream & operator<<(ostream &cout, Person p)
{
cout << " m_A = " << p.m_A << " m_B = " << p.m_B << endl;
return cout;
}
int main()
{
Person p(10, 20);
cout << p << endl;
cout << ++p << endl;
cout << p++ << endl;
}
- 函数调用运算符():
自选返回类型 operator()(自选形参);
#include
using namespace std;
class Person
{
public:
Person(int a, int b): m_A(a), m_B(b)
{
}
void operator()()
{
cout << "here" << endl;
}
int m_A;
int m_B;
};
int main()
{
Person p(10, 20);
p();
}
- 其他不赘述,仅给出 函数名称和参数返回类型
- 赋值运算符=:
Person& operator=(Person p);
- 关系运算符==:
bool operator==(Person p);
【黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难】