运算符 != 不匹配(操作数类型为指针和对象)
No match for operator != (operands types are pointer and object)
我正在重载 ==
和 !=
运算符,并希望后者引用前者,以便完全不重复任何代码。这是我写的:
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);
}
我正在重载 ==
和 !=
运算符,并希望后者引用前者,以便完全不重复任何代码。这是我写的:
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);
}