【发布时间】:2011-04-17 03:23:21
【问题描述】:
我在已经重载的运算符中使用重载运算符时遇到了一点问题。在下面的代码中,我重载了 && 运算符来比较两个 Course 对象。运算符依次转到一个函数,该函数调用其他重载运算符来比较该对象的私有对象变量,以便主要比较它们:
代码:
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;
}
正如一位朋友所建议的,但这甚至无法编译(与重载的 && 运算符的参数不匹配)。
【问题讨论】:
-
您真的不想重载
&&运算符。你的意思是超载==,也许? -
不,我是说 &&。对于作业,我必须使用 && 来测试重叠。 == 用于精确匹配。
标签: c++ operator-overloading overloading operator-keyword