c++中的bool运算符
bool operator in c++
以下是我在初学者文件中找到的代码片段
struct TriIndex //triangle index?
{
int vertex; //vertex
int normal; //normal vecotr
int tcoord; //
bool operator<( const TriIndex& rhs ) const {
if ( vertex == rhs.vertex ) {
if ( normal == rhs.normal ) {
return tcoord < rhs.tcoord;
} else {
return normal < rhs.normal;
}
} else {
return vertex < rhs.vertex;
}
}
};
我以前从未在结构中看到过布尔运算符。有人能向我解释一下吗?
TL;DR:函数内部的代码正在评估*this
是否为<
rhs
,bool
是否只是返回类型。
运算符是operator <
,它是小于运算符。当前对象被认为是左手边或lhs
,与之相比,a < b
表达式的右手边的对象是rhs
。
bool // return type
operator < // the operator
(const TriIndex& rhs) // the parameter
{
...
}
如果当前对象是less than
(应在容器等中先行),则返回true
—<
之后的对象,表达式如下:
if (a < b)
扩展到
if ( a.operator<(b) )
是布尔运算符:
operator bool () const { ... }
其被期望确定对象是否应该评估为真:
struct MaybeEven {
int _i;
MaybeEven(int i_) : _i(i_) {}
operator bool () const { return (_i & 1) == 0; }
};
int main() {
MaybeEven first(3), second(4);
if (first) // if ( first.operator bool() )
std::cout << "first is evenn";
if (second) // if ( second.operator bool() )
std::cout << "second is evenn";
}
bool operator<( const TriIndex& rhs )
这行代码定义了用户定义的数据类型的比较。这里,bool
是该定义将返回的值的类型,即true
或false
。
const TriIndex& rhs
此代码告诉编译器使用结构对象作为参数。
if ( vertex == rhs.vertex ) {
if ( normal == rhs.normal ) {
return tcoord < rhs.tcoord;
} else {
return normal < rhs.normal;
}
} else {
return vertex < rhs.vertex;
}
上面的代码定义了比较的标准,即当您说struct a < struct b
时,编译器应该如何比较两者。这也称为比较运算符重载。
TL-DR;因此,在定义运算符后,当您编写代码时,请说:
if (a < b) {
.......
}
其中a和b是类型CCD_ 16。然后编译器将在定义内执行if-else操作,并使用返回值。如果return = true
,则(a<b)为true,否则条件将为false。
该代码允许您将不同的TriIndexes与<操作员:
TriIndex alpha;
TriIndex beta;
if (alpha < beta) {
etc;
}
bool operator<( const TriIndex& rhs )
是"小于"运算(<
),bool
是"小于"运算符的返回类型。
C++允许重写结构和类的运算符,如<
。例如:
struct MyStruct a, b;
// assign some values to members of a and b
if(a < b) {
// Do something
}
这个代码的作用是什么?这取决于如何为MyStruct
定义"小于"运算符。基本上,当您执行a < b
时,它将为该结构调用"小于"运算符,b
是rhs
(右手边)或您调用的第一个参数,尽管rhs
是典型的约定。
- 为什么 C++ 11 在 ios 类中添加了运算符 bool
- 返回 bool 作为 CPP 中 bool 运算符 [] 中的值
- 当 Type = bool 时,运算符 bool() 与模板 Type() 运算符冲突
- 在C++中重载运算符时,为什么T*优先于bool
- 在类外部定义显式运算符 bool() 时出错
- 在使用C 中使用多个三元运算符时,BOOL和ENUM类型超载的功能没有区分
- Visual Studio无法在布尔运算的上下文中实例化强制转换运算符模板(T=bool)
- isSet() 或运算符 void*() 或显式操作程序 bool() 或其他东西
- 扩展模板化类以在对象实例上具有运算符 bool<bool>
- VS2012 std::函数运算符 bool 意外返回 true
- 运算符 |= 在 std::vector <bool>上
- 为什么显式运算符 bool 允许我转换为任何基元类型
- 在包含向量的<bool>类中重新定义运算符 []
- 重载到bool运算符的非成员转换
- 为什么当bool = true时补码运算符不起作用?
- 自定义实现具有位表示的bool向量-如何实现运算符[]
- diab 5.7编译器中的逻辑与运算符返回非bool类型
- C++ bool std::运算符 < 键映射错误 std::unordered_set<int,std::hash<int>>
- 为什么运算符 char*() 在布尔上下文中覆盖运算符 bool() 常量
- 未定义向量的元素的运算符 &=<bool>?