
C 中的|运算符重载详解1. 什么是|运算符重载|是 C 中的按位或运算符Bitwise OR。通过运算符重载我们可以让自定义类型类/结构体也支持|操作赋予它符合语义的行为。|是一个二元运算符重载时可以写成成员函数ReturnType operator|(const OtherType other) const;左操作数是this非成员函数友元/自由函数ReturnType operator|(const T a, const T b);更推荐支持隐式转换2. 典型应用场景|重载在 C 中最常见的用途是组合标志位Flags比如Qt 中的Qt::AlignmentFlagQt::AlignLeft | Qt::AlignTopstd::ios::openmodestd::ios::in | std::ios::out自定义权限/选项系统3. 关键点要点说明返回值通常返回新对象值而非引用参数用const避免拷贝const 修饰成员函数版应加const不修改自身常与、|、^一起重载形成完整位运算族不要滥用只在语义清晰如标志位时重载避免歧义#include iostream #include string class Permissions { private: unsigned int flags_; public: // 权限枚举每个值对应一个二进制位 enum Flag { None 0, Read 1 0, // 0001 Write 1 1, // 0010 Execute 1 2 // 0100 }; // 构造函数允许从 Flag 隐式构造 Permissions(unsigned int f None) : flags_(f) {} // 重载 | 组合两个权限返回新对象 Permissions operator|(const Permissions other) const { return Permissions(flags_ | other.flags_); } // 重载 判断是否包含某个权限 Permissions operator(const Permissions other) const { return Permissions(flags_ other.flags_); } // 重载 | 就地组合 Permissions operator|(const Permissions other) { flags_ | other.flags_; return *this; } // 判断是否含有某个权限 bool has(Flag f) const { return (flags_ f) ! 0; } // 便于打印 std::string toString() const { std::string s; if (has(Read)) s R; if (has(Write)) s W; if (has(Execute)) s X; return s.empty() ? (none) : s; } }; int main() { Permissions r(Permissions::Read); Permissions w(Permissions::Write); Permissions x(Permissions::Execute); // 使用 operator| Permissions rw r | w; std::cout r | w rw.toString() \n; // RW // 链式组合 Permissions rwx r | w | x; std::cout r | w | x rwx.toString() \n; // RWX // 使用 operator| Permissions p(Permissions::Read); p | Permissions::Execute; std::cout p (R | X) p.toString() \n; // RX // 使用 operator 判断 std::cout rwx w ? ((rwx w).toString()) \n; // W // has() 检查 std::cout rwx has Write? (rwx.has(Permissions::Write) ? yes : no) \n; std::cout r has Write? (r.has(Permissions::Write) ? yes : no) \n; return 0; }