c++中的bool运算符

bool operator in c++

本文关键字:运算符 bool 中的 c++      更新时间:2023-10-16

以下是我在初学者文件中找到的代码片段

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是否为< rhsbool是否只是返回类型。

运算符是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是该定义将返回的值的类型,即truefalse


 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时,它将为该结构调用"小于"运算符,brhs(右手边)或您调用的第一个参数,尽管rhs是典型的约定。