首页 > 解决方案 > 运算符 != 不匹配(操作数类型为指针和对象)

问题描述

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

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是不是 aDate而是 a Date*。有没有办法在this Date没有指针或使用thiswith的情况下引用other Date

标签: c++c++11pointersoperator-overloadingthis

解决方案


取消引用指针:

return !(*this == other);

推荐阅读