我在已经重载的运算符中使用重载运算符时遇到了一个问题。在下面的代码中,我重载了&&运算符以比较两个Course对象。运算符又转到一个函数,该函数调用其他重载的运算符以比较该对象的私有(private)对象变量,从而主要将它们进行比较:
码:
bool operator&&(const DaysOfWeek& a, const DaysOfWeek& b);
bool operator&&(const TimeInterval& a, const TimeInterval& b);
现在,我的问题。我在该项目中使用了许多重载运算符,但这是我第一次必须在其他重载运算符中调用重载运算符。不幸的是,我的isOverlap函数没有调用上面代码中的重载运算符。所以我的问题是:为什么会这样,我该如何纠正?
任何帮助将不胜感激,因为我将头撞在墙上,试图使它起作用。我已经包括Course.h中的相关事件代码以及Course.cpp中的函数和重载运算符。我已经加粗了我有不规则输出的相应代码行(不使用我的重载运算符)。
码:
bool Course::isOverlap(const Course& b) const
{
DaysOfWeek tempDays = b.getDays();
TimeInterval tempTime = b.getTime();
if(this->instructor==b.getInstructor() &&
&this->days&&(&tempDays) &&
&this->time&&(&tempTime))
{
return true;
}
else
return false;
}
bool operator&&(const Course& a, const Course& b)
{
if (a.isOverlap(b))
return true;
else
return false;
}
码:
#ifndef COURSE_H
#define COURSE_H
#include <string>
#include "TimeInterval.h"
#include "DaysOfWeek.h"
using namespace std;
class Course
{
public:
Course();
Course(const string courseCode, const string section,
const DaysOfWeek& days, const TimeInterval& time,
const string instructor);
void setCourse(string courseCode, string section,
DaysOfWeek& days, TimeInterval& time, string instructor);
string getCourse() const;
string getSection() const;
DaysOfWeek getDays() const;
TimeInterval getTime() const;
string getInstructor() const;
bool isOverlap(const Course& b) const;
bool isMatch(const Course& b) const;
private:
string courseCode;
string section;
DaysOfWeek days;
TimeInterval time;
string instructor;
};
bool operator&&(const Course& a, const Course& b);
bool operator==(const Course& a, const Course& b);
#endif //COURSE_H
我也尝试过用以下代码替换代码:
bool Course::isOverlap(const Course& b) const
{
DaysOfWeek tempDays = b.getDays();
TimeInterval tempTime = b.getTime();
if(instructor==b.getInstructor() &&
days && tempDays &&
time && tempTime)
{
return true;
}
else
return false;
}
正如一个 friend 所建议的那样,但这甚至无法编译(与重载的&&运算符的参数不匹配)。
最佳答案
这个:
instructor==b.getInstructor() && days && tempDays && time && tempTime
等效于此:
(((((instructor==b.getInstructor()) && days) && tempDays) && time) && tempTime)
首先评估
instructor==b.getInstructor()
,产生bool
。然后,编译器将看到&& days
,并尝试查找&&
的重载,该重载需要bool
和DaysOfWeek
。没有一个,因此会产生错误。要将重载的
&&
与内置&&
一起使用,您需要一些括号来强制对子表达式进行分组:instructor==b.getInstructor() && (days && tempDays) && (time && tempTime)
^ ^ ^ ^
也就是说,我强烈建议您回到您的教练那里,并告诉他他疯了。重载
&&
运算符(或||
运算符)几乎总是错误的,因为它破坏了该运算符的常规语义(重载时,这两个运算符将停止短路)。关于c++ - 已重载运算符中的C++运算符重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5691219/