就是赋予运算符新的意义,比如 << 既可以当作左移运算符,又可以当初输出运算符。
注意:重载可以发生在类的外边,也可以作为类的的成员函数。
#include using namespace std;class Complex
{//friend Complex operator+(const Complex &c1, const Complex &c2);
private:int a; //实部int b; //虚部
public:Complex(int _a, int _b){this->a = _a;this->b = _b;}void print(){cout << a << " + " << b << "i" << endl;}Complex operator+(const Complex &c){Complex t(0, 0);t.a = this->a + c.a;t.b = this->b + c.b;return t;}
};//运算符重载本质就是函数的重载
/*Complex operator+(const Complex &c1, const Complex &c2)
{Complex t(0, 0);t.a = c1.a + c2.a;t.b = c1.b + c2.b;return t;
}*/int main()
{Complex c1(1, 2);Complex c2(2, 3);c1.print();//c1 + c2;Complex t(0, 0);//t = operator+(c1, c2);t = c1 + c2; //编译器会转换成 t = c1.operator+(c2)t.print();return 0;
}
运行结果:
要明白前置++ 和 后置++ 的区别
++ 运算符的重载:
示例代码:
#include using namespace std;class Complex
{friend ostream &operator<<(ostream &out, const Complex &c);
private:int a; //实部int b; //虚部
public:Complex(int _a, int _b){this->a = _a;this->b = _b;}//后置++Complex operator++(int) //通过占位参数来构成函数重载{Complex t = *this;this->a++;this->b++;return t;}//前置++Complex &operator++(){this->a++;this->b++;return *this;}
};ostream &operator<<(ostream &out, const Complex &c)
{out << c.a << " + " << c.b << "i";return out;
}int main()
{Complex c1(1, 2);cout << c1++ << endl;cout << ++c1 << endl;return 0;
}
运行结果:
全局函数、类成员函数方法实现运算符重载步骤
1)要承认操作符重载是一个函数,写出函数名称operator+ ()
2)根据操作数,写出函数参数
3)根据业务,完善函数返回值(看函数是返回引用还是指针 元素),及实现函数业务
示例代码:
#include using namespace std;class Complex
{friend ostream &operator<<(ostream &out, const Complex &c);
private:int a; //实部int b; //虚部
public:Complex(int _a, int _b){this->a = _a;this->b = _b;}void print(){cout << a << " + " << b << "i" << endl;}/*ostream &operator<<(ostream &out) //如果左操作数不能修改,则不能重载成成员函数{out << this->a << " + " << b << "i";return out;}*/
};ostream &operator<<(ostream &out, const Complex &c)
{out << c.a << " + " << c.b << "i";return out;
}int main()
{Complex c1(1, 2);c1.print();cout << c1 << endl; //operator<<(operator<<(cout, c1), endl); 等价于 cout.operator<<(c1)return 0;
}
运行结果:
上一篇:MySQL知识点总结(2)