C++运算符重载
文章目录
C++运算符号重载
接下来构建一个复数类来说明运算符重载,该类含有两个成员变量
- 实数部分
real
- 虚数部分
imag
1.类的定义以及函数的声明
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Complex
{
public:
int real, imag;
Complex() : real(0), imag(0) {}
Complex(int r) : real(r), imag(0) {}
Complex(int r, int i) : real(r), imag(i) {}
Complex(const Complex &t);
~Complex(){};
// 二元运算符(+ - / * % == > < )重载举例
friend Complex operator+(const Complex &t, const Complex &p);
friend bool operator==(const Complex &t, const Complex &p);
// 一元运算符重载举例
friend Complex operator-(const Complex &t);
Complex &operator++(); // 前置自增运算符
Complex operator++(int); // 后置自增运算符
friend istream &operator>>(istream &cin, Complex &t); // 重载 >>
friend ostream &operator<<(istream &cout, const Complex &t); // 重载 <<
};
// 拷贝构造函数
Complex::Complex(const Complex &t)
{
real = t.real;
imag = t.imag;
}
2. 加号运算符 + 重载
/ 重载+ 号
Complex operator+(const Complex &t, const Complex &p)
{
return Complex(p.real + t.real, p.imag + t.imag);
}
3. 取反运算符号 - 重载
// 重载取反符号 -
Complex operator-(const Complex &t)
{
Complex temp(-t.real, -t.imag);
return temp;
}
4. 相等运算符 == 重载
// 重载==号
bool operator==(const Complex &t, const Complex &p)
{
return ((t.real == p.real) && (t.imag == p.imag));
}
5. 前置自增运算符重载 ++A
// 重载 前置自增加运算符
Complex &Complex::operator++()
{
this->real++;
this->imag++;
return *this; // 需要返回this自增之后的结果,直接返回this用引用接收
}
6. 后置自增运算符重载 A++
// 重载 后置自增加运算符
Complex Complex::operator++(int)
{
Complex temp(*this);
this->real++;
this->imag++;
return temp; // 需要返回this自增之前的结果,所以用临时变量返回
}
7. << 和 >> 运算符重载
// 重载 >>
istream &operator>>(istream &cin, Complex &t)
{
cin >> t.real >> t.imag;
return cin;
}
// 重载 <<
ostream &operator<<(ostream &cout, const Complex &t)
{
cout<<t.real;
if(t.imag>0)
cout<<"+";
else if(t.imag==0)
return cout;
cout<<t.imag<<"i"<<endl;
return cout;
}
8.测试
int main()
{
Complex a(2, 2), b(2, 2);
Complex c(a); // 拷贝构造
cout << a << endl; // 2+2i
c = a + b; // 重载 + 号
cout << c << endl; // 4+4i
cout << (b == a) << endl; // 1
c = c + 20; // 有对应的构造函数,会自动执行特定的类型转换。
cout << c << endl; // 24+4i
a = -a;
cout << a << endl; // -2-2i
b++;
cout << b << endl; // 3+3i
++b;
cout << b << endl; // 4+4i
cin >> b; //输入
cout << b << endl;
return 0;
}
运算符重载为全局函数时,参数的个数等于运算符的目数(即操作数的个数);
运算符重载为成员函数时,参数的个数等于运算符的目数减一。
可将操作符号作为类的友元,虽然着并非必须的。