一、运算符重载
将双目运算符重载为成员函数:
#include <iostream> using namespace std; class Complex { public: Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { } //运算符+重载成员函数 Complex operator + (const Complex &c2) const; //运算符-重载成员函数 Complex operator - (const Complex &c2) const; void display() const; //输出复数 private: double real; //复数实部 double imag; //复数虚部 }; Complex Complex::operator+(const Complex &c2) const{ //创建一个临时无名对象作为返回值 return Complex(real + c2.real, imag + c2.imag); } Complex Complex::operator-(const Complex &c2) const{ //创建一个临时无名对象作为返回值 return Complex(real - c2.real, imag - c2.imag); } void Complex::display() const { cout << "(" << real << ", " << imag << ")" << endl; } int main() { Complex c1(5, 4), c2(2, 10), c3; cout << "c1 = "; c1.display(); cout << "c2 = "; c2.display(); c3 = c1 - c2; //使用重载运算符完成复数减法 cout << "c3 = c1 - c2 = "; c3.display(); c3 = c1 + c2; //使用重载运算符完成复数加法 cout << "c3 = c1 + c2 = "; c3.display(); return 0; }
将单目运算符重载为成员函数:
为了在程序中区分前置运算符(前置++)和后置++,需要在后置++的参数列表里面加东西来区分。
#include <iostream> using namespace std; class Clock {//时钟类定义 public: Clock(int hour = 0, int minute = 0, int second = 0); void showTime() const; //前置单目运算符重载 Clock& operator ++ (); //后置单目运算符重载 Clock operator ++ (int); private: int hour, minute, second; }; Clock::Clock(int hour, int minute, int second) { if (0 <= hour && hour < 24 && 0 <= minute && minute < 60 && 0 <= second && second < 60) { this->hour = hour; this->minute = minute; this->second = second; } else cout << "Time error!" << endl; } void Clock::showTime() const { //显示时间 cout << hour << ":" << minute << ":" << second << endl; } Clock & Clock::operator ++ () { second++; if (second >= 60) { second -= 60; minute++; if (minute >= 60) { minute -= 60; hour = (hour + 1) % 24; } } return *this; } Clock Clock::operator ++ (int) { //注意形参表中的整型参数 Clock old = *this; ++(*this); //调用前置“++”运算符 return old; } int main() { Clock myClock(23, 59, 59); cout << "First time output: "; myClock.showTime(); cout << "Show myClock++: "; (myClock++).showTime(); cout << "Show ++myClock: "; (++myClock).showTime(); return 0; }
运算符重载为非成员函数: