运算符重载可以通过定义成员函数和定义非成员函数两种方式实现。在类里面定义成员函数即可直接访问private的数据,在类外定义运算符重载函数为非成员函数,不可以直接访问类的private,若想在类外定义重载函数且直接访问private,可在类内声明友元函数。注意有些运算符只能通过成员函数重载,如=,[],(),->
1.通过运算符重载实现复数加减法、判断和取相反数各种操作
代码(写得有点乱,主要是为了测试)
#includeusing namespace std; class Complex { public: Complex(double a, double b) { imag = b; real = a; } Complex() { real = 0; imag = 0; } ~Complex(); Complex operator + (const Complex& x)const//运算符重载实现复数相加 { Complex temp; temp.real = real + x.real; temp.imag = imag + x.imag; return temp; } void display(); bool operator ==(const Complex& x)const//运算符重载实现判断复数相等 { return (real == x.real) && (imag == x.imag); } bool operator !=(const Complex& x)const//判断复数不等 { return !(*this == x); } friend Complex operator +(const Complex& c1, double d);//全局函数运算符重载实现复数与实数相加 Complex operator -()const//运算符重载实现复数实部和虚部同时取相反数 { Complex temp; temp.real = -real; temp.imag = -imag; return temp; } friend bool operator !(const Complex& c);//判断复数是否为0 private: double real; double imag; }; Complex::~Complex() { } void Complex::display() { cout << real << "+" << imag << "i" << endl; } Complex operator+(const Complex& c, double d) { return Complex(c.real, c.imag + d); } bool operator!(const Complex& c) { return (c.real == 0.0) && (c.imag == 0.0); } int main() {//测试函数样例 double d=2.2; Complex a(1.0, 2.0), b(3.0, 4.0), c,e,f; c = a + b; a.display(); b.display(); cout << "a+b="; c.display(); cout << "判断a,b是否相等n"; if (a == b)cout << "ab相等n"; else cout << "不相等n"; cout << "判断a是否为0n"; if (!a)cout << "a是0"; else cout << "a不是0"; cout << "将a置为相反数n"; f = -a; f.display(); cout << "复数与实数相加n"; cout << "a+d="; e=a+d; e.display(); return 0; }
2.有⼀个Time类,包含数据成员hour(时)、minute(分)和sec(秒),现模拟两个时⻓的相加,每满60秒进1分钟,每满60分进1⼩时,每满24⼩时则归0。时位的合法取值范围为[0,23],分位和秒位的合法取值范围为[0,59]。 要求输出时、分、秒的值。请完成运算符+的重载。
例如:5⼩时35分钟+19⼩时20分钟=0⼩时55分钟
#includeusing namespace std; class Time { public: Time(); Time(int h, int m, int s) :hour(h), min(m), sec(s) {} Time operator +(const Time t)const { Time temp; if (t.sec + sec >= 60) { temp.sec = t.sec + sec - 60; temp.min += 1; } else { temp.sec = t.sec + sec; } if (temp.min + t.min + min >= 60) { temp.min += t.min + min - 60; temp.hour += 1; } else { temp.min += t.min + min; } if (temp.hour + t.hour + hour >= 24) { temp.hour += t.hour + hour - 24; } else { temp.hour += t.hour + hour; } return temp; } ~Time(); void display(); private: int hour; int min; int sec; }; Time::Time() { hour = 0; min = 0; sec = 0; } Time::~Time() { } void Time::display() { cout << hour << "时" << min << "分" << sec << "秒n"; } int main() { Time a(12, 5, 36), b(19, 20, 34), c(5, 35, 0), d, e; a.display(); b.display(); c.display(); d = a + b; e = b + c; cout << "a+b="; d.display(); cout << "b+c="; e.display(); return 0; }



