You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++重载operator&&、operator||及其返回类型实现问题

实现方案

你需要在Example类中重载&&、||运算符,同时添加到std::string的隐式类型转换即可,完整实现如下:

#include <string>

class Example
{
public:
    Example(std::string _a): a(std::move(_a)) {}
    
    // 重载&&运算符,拼接两个Example的存储字符串
    Example operator&&(const Example& other) const {
        return Example(a + "&&" + other.a);
    }
    
    // 重载||运算符,拼接两个Example的存储字符串
    Example operator||(const Example& other) const {
        return Example(a + "||" + other.a);
    }
    
    // 隐式转换为std::string,支持直接赋值给string变量
    operator std::string() const {
        return a;
    }

    std::string a;
};

测试代码验证效果:

#include <iostream>

int main() {
    Example test("a"), test2("b"), test3("c");
    std::string result = test && test2 || test3;
    std::cout << result << std::endl; // 输出结果为 a&&b||c
    return 0;
}

注意事项

  • 重载后的&&和||不具备原生运算符的短路求值特性,所有参与运算的操作数都会被完整求值
  • 重载运算符优先级和原生保持一致:&&优先级高于||,因此运算顺序为(test && test2) || test3,刚好匹配你需要的拼接顺序
  • 如果需要支持和字符串字面量直接运算,可额外补充接受std::string类型参数的运算符重载版本。

内容的提问来源于stack exchange,提问作者Ovidiu Firescu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:45:03