c ++中的bool运算符

时间:2015-06-25 01:47:33

标签: 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;
        }
    }
};

我之前从未在结构体内看过bool运算符。任何人都可以向我解释这个吗?

4 个答案:

答案 0 :(得分:3)

TL; DR:函数内部的代码正在评估*this< rhsbool仅仅是返回类型。

运算符是operator <,它是小于运算符。当前对象被视为左侧lhs,并且与a < b表达式的右侧进行比较的对象为rhs

bool  // return type
operator <  // the operator
(const TriIndex& rhs) // the parameter
{
    ...
}

如果当前对象为true(应在容器之前,等等),则返回less than表达式中<之后的对象:

if (a < b)

扩展为

if ( a.operator<(b) )

bool运算符:

operator bool () const { ... }

预计将确定对象是否应评估为true:

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 even\n";
    if (second) // if ( second.operator bool() )
        std::cout << "second is even\n";
}

答案 1 :(得分:0)

该代码允许您将不同的TriIndex与&lt;操作者:

TriIndex alpha;
TriIndex beta;

if (alpha < beta) {
   etc;
}

答案 2 :(得分:0)

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(右手边)或任何你称之为第一个参数的结构调用“小于”运算符,尽管{{} 1}}是典型的惯例。

答案 3 :(得分:0)

  bool operator<( const TriIndex& rhs )

这行代码定义了 用户定义的数据类型 的比较。此处bool是此定义将返回的值的类型,即truefalse

 const TriIndex& rhs 

此代码告诉编译器使用 struct object 作为参数。

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的类型为struct fam。然后编译器将在定义中执行 if else 操作并使用返回值。如果return = true则(a&lt; b) true ,否则条件将 false

相关问题