C++是运算符!=定义运算符==时自动提供
C++ is operator!= automatically provided when operator== defined
我想知道运算符是不是!=在我的类中定义运算符==时自动提供?当我在类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: ...
否,!=不是根据==自动定义的。在中定义了一些泛型,有助于定义==和<的所有运算符;,虽然
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 如何正确实现和访问运算符的各种自定义枚举器
- 自定义先决条件对移动分配运算符有效吗
- 在运算符重载定义中使用成员函数(const错误)
- g++用户定义的动态链接库上的全局new和delete运算符
- 一元"运算符"未在C++中定义
- STL按客户"<"运算符对向量进行排序。为什么要将"<"运算符定义为 const?
- 如何将运算符定义从头文件添加到现有结构?
- 在使用具有相等运算符定义的抽象类时,如何定义父类以减少代码重复?
- 当我们没有将运算符+定义为朋友时?C++
- 没有返回值的c++类成员运算符定义
- 用指向对象的指针和c++中的new运算符定义对象
- <T> 仅为具有运算符/定义的此类 T 创建模板
- 基类中的运算符定义
- C++:不同名称空间中的多个运算符定义
- 运算符定义不能正常工作
- 类运算符'='定义
- 为什么VS不为逻辑运算符定义可选的令牌?
- std::equal_range 不适用于具有运算符<定义的结构