【Tips】C++语言程序设计
@运算符重载
#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 oeprator- (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 {
std::cout << "(" << real << ", " << imag << ")" << std::endl;
}
int main() {
Complex c1(5, 4), c2(2, 10), c3;
std::cout << "c1=";c1.display();
std::cout << "c2=";c2.diaplay();
c3=c1-c2;
std::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) {
this->hour = hour;
this->minute = minute;
this->second = second;
}
void Clock::showTime() {
std::cout << hour << ":" << minute << ":" << second << std::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++(this) {
Clock old = *this;
++(*this);
return old;
}
int main() {
Clock myClock(23, 59, 59);
std::cout << "Fist time output: ";
myClock.showTime();
std::cout << "Show myClock++: ";
(myClock++).showTime();
std::cout << "Show++myClock: ";
(++myClock).showTime();
return 0;
}
@以非成员函数形式重载运算符