C++是运算符!=定义运算符==时自动提供

C++ is operator!= automatically provided when operator== defined

本文关键字:运算符 定义 C++      更新时间:2023-10-16

我想知道运算符是不是!=在我的类中定义运算符==时自动提供?当我在类A中定义运算符==时,显然A A、A b、A==b有效,但A!=b没有。然而,我不确定这种情况是否总是发生。这方面有什么例外吗?

否,运算符(除了赋值(从不自动生成。用==:来定义它很容易

bool operator!=(A const & l, A const & r) {return !(l == r);}

运算符!=不是自动为您提供的。如果您想要这样的自动化,您可能想了解rel_ops命名空间。本质上你可以说

using namespace std::rel_ops;

在使用CCD_ 3之前。

自从C++20以来,这是真的。早期的C++标准版本不提供运算符!=来自运算符==自动。

由于明显的原因,语言没有提供您想要的内容。您想要的是由boost::operators:提供的

class MyClass : boost::operators<MyClass> {
    bool operator==(const MyInt& x) const;
}

将基于您的operator==()

为您获得operator!=()

如果是#include <utility>,则可以指定using namespace std::rel_ops

执行此操作将自动从operator ==定义operator !=,并从operator <定义operator <=operator >=operator >

没有。你必须明确地定义它。

代码:

#include <iostream>
using namespace std;
class a
{
    private:
        int b;
    public:
        a(int B): b(B)
        bool operator == (const a & other) { return this->b == other.b; }
};
int main()
{
    a a1(10);
    a a2(15);
    if (a1 != a2)
    {
        cout << "Not equal" << endl;
    }
}

输出:

[ djhaskin987@des-arch-danhas:~ ]$ g++ a.cpp
a.cpp: In constructor ‘a::a(int)’:
a.cpp:11:9: error: expected ‘{’ before ‘bool’
         bool operator == (const a & other) { return this->b == other.b; }
         ^
a.cpp: In function ‘int main()’:
a.cpp:18:12: error: no match for ‘operator!=’ (operand types are ‘a’ and ‘a’)
     if (a1 != a2)
            ^
a.cpp:18:12: note: candidates are: ...

否,!=不是根据==自动定义的。在中定义了一些泛型,有助于定义==和<的所有运算符;,虽然