operator std::string() const?

前端 未结 2 1987
清酒与你
清酒与你 2020-12-28 13:21

Can somebody tell me what precisely

operator std::string()

stands for?

2条回答
  •  情话喂你
    2020-12-28 13:48

    It is a cast operator. Any class that defines this type can be used anywhere a std::string is required. For instance,

    class Foo {
    public:
        operator std::string() const { return "I am a foo!"; }
    };
    ...
    Foo foo;
    std::cout << foo; // Will print "I am a foo!".
    

    Cast operators are almost always a bad idea, since there is invariably a better way to achieve the same result. In the above case, you are better off defining operator<<(std::ostream&, const Foo&).

提交回复
热议问题