不匹配运算符!=(操作数类型是指针和对象)

问题描述 投票:2回答:3

我正在重载==!=运算符,并希望后者引用前者,以便根本不重复任何代码。这是我写的:

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或将thisother Date一起使用?

c++ c++11 pointers operator-overloading this
3个回答
5
投票

取消引用指针:

return !(*this == other);

1
投票

您可以尝试像这样重载!=函数:

bool Date :: operator != (const Date & other) const {
    return !(*this == other);
}

0
投票

您需要取消引用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);
}
© www.soinside.com 2019 - 2024. All rights reserved.