C++ 重载运算符同时作为成员和函数?我正在尝试在这里设置运算符重载。
在每种情况下,我都没有将 operator+ 重载为朋友和成员的问题。但是,当我尝试同时将 + 运算符作为朋友重载和将朋友作为成员重载时,我得到了错误。
这里有点困惑。我可能会尝试做一些甚至没有意义的事情?请检查我的代码,看看我是否可以解决。情况 3 是产生错误的情况。谢谢!
CASE1重载为朋友:Source.cpp
#include <iostream>
using namespace std;
#include "Time.h"
int main () {
Time planning; Time coding(2, 40);
Time fixing(5, 55); Time total;
total = coding + fixing;
cout << "coding + fixing = ";
total.Show();
cout << endl;
cin.get(); return 0; }
CASE1作为朋友重载:Time.h
#pragma once
class Time
{ int hours; int minutes;
public:
Time(void);
~Time(void);
Time(int, int m = 0);
void AddMin(int);
void AddHr(int);
void Reset(int h=0, int m=0);
friend const Time operator+(const Time&, const Time&);
void Show() const; };
CASE1重载为朋友:Time.cpp
#include "Time.h"
#include <iostream>
using namespace std;
Time::Time(void) { hours = minutes = 0;}
Time::~Time(void) {}
Time::Time (int h, int m) { hours =h; minutes = m; }
void Time::AddMin(int m) {minutes+=m; hours+=minutes/60; minutes%= 60; }
void Time::Reset(int h, int m) {hours = h; minutes = m;}
const Time operator+(const Time & t1, const Time& t2) {
Time sum;
sum.minutes = t1.minutes + t2.minutes;
sum.hours = t1.hours + t2.hours + sum.minutes / 60;
sum.minutes %= 60;
return sum; }
void Time::Show() const
{ cout << hours << " hours, " << minutes << " minutes"; }
CASE2作为成员重载:Source.cpp / Time.h / Time.cpp Source.cpp // 相同
时间.h
const Time operator+(const Time&) const; // declaration
时间.cpp
const 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; } // function definition
案例3:错误;试图同时重载运算符 + 作为朋友和成员 Source.cpp // 相同
时间.h
friend const Time operator+(const Time&) ; // declaration
时间.cpp
friend const Time operator+(const Time& t) {
Time sum;
sum.minutes = minutes + t.minutes;
sum.hours = hours + t.hours + sum.minutes / 60;
sum.minutes %= 60;
return sum; } // function definition