我正在重载==
和!=
运算符,并希望后者引用前者,以便根本不重复任何代码。这是我写的:
bool Date :: operator == (const Date & other) const {
bool are_equal = Year() == other.Year();
for (int i=0; i<other.NumEvents() && are_equal; i++)
are_equal = this[i] == other[i];
return are_equal;
}
bool Date :: operator != (const Date & other) const {
return !(this == other);
}
这里最大的问题是this
不是Date
,而是Date*
。有没有办法在没有指针的情况下引用this Date
或将this
与other Date
一起使用?
取消引用指针:
return !(*this == other);
您可以尝试像这样重载!=
函数:
bool Date :: operator != (const Date & other) const {
return !(*this == other);
}
您需要取消引用this
指针,以便在它引用的Date
对象上调用您的运算符,例如:
bool Date :: operator == (const Date & other) const {
bool are_equal = ((Year() == other.Year()) && (NumEvents() == other.NumEvents()));
for (int i = 0; (i < other.NumEvents()) && are_equal; ++i) {
are_equal = ((*this)[i] == other[i]);
}
return are_equal;
}
bool Date :: operator != (const Date & other) const {
return !((*this) == other);
}