C++运算符在已重载的运算符中重载
我在使用重载的运算符时,在已经重载的运算符中遇到了一些问题。在我的下面的代码中,我已经超载了运算符来比较两个课程对象。反过来,运营商进入它调用其他重载运营商私有对象变量比较该对象的给他们比较主要的功能:C++运算符在已重载的运算符中重载
代码:现在
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;
}
作为一个朋友曾建议,但是这并未” t甚至编译(与超载的参数不匹配& &运营商)。
此:
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)
^ ^^ ^
这就是说,我会强烈建议回去给你的老师,并告诉他,他疯了。过载&&
运营商(或||
运营商)几乎总是错误的,因为它打破了运营商的正常语义(当超载时,这两个运营商停止短路)。
非常好!非常感谢您的回答。现在完美的工作!我无法相信这是一些括号问题,但是我再也没有想过要像你说的那样重载&&操作符。 ;) 再次,非常感谢! – Aurum 2011-04-17 03:48:00
DaysOfWeek tempDays = b.getDays();
TimeInterval tempTime = b.getTime();
if(this->instructor==b.getInstructor() &&
&this->days&&(&tempDays) &&
&this->time&&(&tempTime))
在上面使用的是逻辑和的days
地址相比,tempDays
地址,你应该比较对象,而不是地址。与time
和tempTime
一样。
你真的不想重载'&&'操作符。你的意思是重载'==',也许? – 2011-04-17 03:26:35
不,我的意思是&&。对于作业,我必须使用&&来测试重叠。 ==完全匹配。 – Aurum 2011-04-17 03:33:05