1,运算符重载 示例程序如下:
- #ifndef MYTIME1_H_
- #define MYTIME1_H_
- class Time
- {
- private:
- int hours;
- int minutes;
- public:
- Time(int h, int m = 0);
- Time operator+(const Time & t) const;
- void Show() const;
- };
- #endif
- Time::Time(int h, int m )
- {
- hours = h;
- minutes = m;
- }
- Time Time::operator+(const Time & t) const
- {
- Time sum;
- sum.minutes = minutes + t.minutes;
- sum.hours = hours + t.hours + sum.minutes / 60;
- sum.minutes %= 60;
- return sum;
- }
- void Time::Show() const
- {
- std::cout << hours << " hours, " << minutes << " minutes";
- }
- int main()
- {
- using std::cout;
- using std::endl;
- Time coding(2, 40);
- Time fixing(5, 55);
- Time total;
- total = coding + fixing;
- // operator notation
- cout << "coding + fixing = ";
- total.Show();
- cout << endl;
- return 0;
- }
2友元函数 通过让函数称为类的友元,可以赋予该函数与类的成员函数相同的访问权限 创建友元函数 1,将函数声明放在类的声明中,并再原型前面加上关键字friend friend Time operator*(double m,const Time &t); 2,编写友元函数的定义,编写定义的时候不需要在前面加上friend关键字,也不需要类限定符Time:: 总之,类的友元函数是非成员函数,其访问权限和成员函数相同