首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么C++表达式会涉及重载运算符和隐式转换?

为什么C++表达式会涉及重载运算符和隐式转换?

提问于 2018-01-29 23:57:25
回答 2关注 0查看 421

有谁能解释一下为什么boolif (a < 0)表达式可以作为特定的运算符,是否有解决办法?

代码语言:txt
复制
struct Foo {
    Foo() {}
    Foo(int x) {}

    operator bool() const { return false; }

    friend bool operator<(const Foo& a, const Foo& b) {
        return true;
    }
};

int main() {
    Foo a, b;
    if (a < 0) {
        a = 0;
    }
    return 1;
}

当编译时,得到:

代码语言:txt
复制
g++ foo.cpp
foo.cpp: In function 'int main()':
foo.cpp:18:11: error: ambiguous overload for 'operator<' (operand types are 'Foo' and 'int')
     if (a < 0) {
           ^
foo.cpp:18:11: note: candidate: operator<(int, int) <built-in>
foo.cpp:8:17: note: candidate: bool operator<(const Foo&, const Foo&)
     friend bool operator<(const Foo& a, const Foo& b)

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档