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
相关产品推荐
相关产品推荐

