重载operator<<实现enum class优雅打印,代码中应放置该重载函数于何处?
好的,咱们来聊聊这个enum class的operator<<重载位置问题~其实有几种靠谱的放置方式,我给你拆解清楚:
方案1:全局命名空间下,放在enum class定义之后
这是最常用的做法,因为enum class是强类型枚举,全局的重载函数能直接访问它的枚举值,只要保证在使用这个运算符之前,重载函数已经被声明或定义就行。
补全你的代码示例如下:
#include <iostream> #include <string> #include <memory> enum class property_type {CAR, HOUSE}; // 在这里重载operator<<,放在enum class定义之后 std::ostream& operator<<(std::ostream& os, property_type pt) { switch(pt) { case property_type::CAR: os << "car"; break; case property_type::HOUSE: os << "house"; break; default: os << "unknown property"; } return os; } class Property { public: virtual property_type type() = 0; }; class Car : public Property { public: Car(std::string name) : mName(name) {} std::string mName; property_type type() override { return property_type::CAR; } }; class House : public Property { public: House(std::string address) : mAddress(address) {} std::string mAddress; property_type type() override { return property_type::HOUSE; } }; int main() { std::unique_ptr<Property> myCar = std::make_unique<Car>("Tesla"); std::cout << myCar->type() << std::endl; // 输出:car std::unique_ptr<Property> myHouse = std::make_unique<House>("123 Main St"); std::cout << myHouse->type() << std::endl; // 输出:house return 0; }
方案2:放在enum class所属的自定义命名空间内
如果你的property_type是在某个自定义命名空间里,把重载函数放在同一个命名空间里会更规范,能避免全局命名空间污染。举个例子:
#include <iostream> #include <string> #include <memory> namespace property { enum class property_type {CAR, HOUSE}; // 重载函数放在同命名空间内 std::ostream& operator<<(std::ostream& os, property_type pt) { switch(pt) { case property_type::CAR: os << "car"; break; case property_type::HOUSE: os << "house"; break; default: os << "unknown property"; } return os; } } class Property { public: virtual property::property_type type() = 0; }; class Car : public Property { public: Car(std::string name) : mName(name) {} std::string mName; property::property_type type() override { return property::property_type::CAR; } }; // House类定义类似,这里省略
避坑提醒
- 别把
operator<<重载成类的成员函数(比如放在Property或它的子类里),因为operator<<的左操作数是std::ostream,如果写成成员函数,左操作数就只能是类对象,完全不符合我们直接打印property_type的需求。 - 一定要确保重载函数在被使用前已经被声明或定义,要是把重载放在
main函数后面,就得先提前声明:std::ostream& operator<<(std::ostream&, property_type);
内容的提问来源于stack exchange,提问作者newbie_old
相关产品推荐
相关产品推荐

