【问题标题】:C++ is operator!= automatically provided when operator== definedC++ 是 operator!= 当 operator== 定义时自动提供
【发布时间】:2014-07-24 15:52:19
【问题描述】:

我想知道在我的类中定义 operator== 时是否会自动提供 operator!=?当我在 A 类中定义 operator== 时,显然 A a, A b, a == b 有效,但 a != b 无效。但是我不确定它是否总是发生。有什么例外吗?

【问题讨论】:

标签: c++ operator-overloading


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    using namespace std::rel_ops;
    

    在使用operator !=之前。

    【讨论】:

    • 但是要注意限制 using 指令的范围。它将为所有类型提供运算符,而不仅仅是您感兴趣的类型,这可能会产生令人惊讶的后果。
    【解决方案3】:

    出于显而易见的原因,该语言并未提供您所追求的内容。你想要的boost::operators提供的:

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

    将根据您的 operator==()

    为您提供operator!=()

    【讨论】:

      【解决方案4】:

      从 C++20 开始就是这样。早期的 C++ 标准版本不会自动从 operator== 提供 operator!=。

      【讨论】:

        【解决方案5】:

        如果你#include &lt;utility&gt;,你可以指定using namespace std::rel_ops

        这样做会自动从operator == 定义operator !=,并从operator &lt; 定义operator &lt;=operator &gt;=operator &gt;

        【讨论】:

        • std::rel_ops 有点……broken
        【解决方案6】:

        不。您必须明确定义它。

        代码:

        #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: ...
        

        【讨论】:

          【解决方案7】:

          不,!= 不是根据 == 自动定义的。 有一些泛型定义有助于根据 == 和

          【讨论】:

            猜你喜欢
            • 2021-09-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-09-20
            • 2012-09-29
            相关资源
            最近更新 更多