我可以明确地定义流运算符和转换运算符吗?

时间:2015-04-18 02:11:54

标签: c++

我试图创建一个既有operator<<又有operator>>朋友函数的类,一个operator std::string方法,就像这样:

class MyClass
{
public:
    operator std::string()

    friend std::istream& operator>>(std::istream&, const MyClass&);
    friend std::ostream& operator<<(std::ostream&, const MyClass&);
};

我发现我的编译器抱怨&#34;模糊的重载&#34;当我尝试使用它们时的流操作符。我认为是因为如果我写这个:

myStream << MyClass();

编译器不知道是使用operator<< MyClass还是首先使用operator std::string MyClass,然后使用{{ 1}}用于operator<<(在标准库中定义)写入流。

这实际上是原因吗?如果是这样,有没有办法解决它?我知道在C ++ 11中你可以在转换运算符上使用std::string关键字来防止隐式转换,但我正在处理的项目目前编译为C ++ 03。

1 个答案:

答案 0 :(得分:1)

首先,自1998年标准以来,关键字显式已经存在。你确定你的编译器不支持吗?

此外,我对你的解释持怀疑态度,因为表达式std :: cout&lt;&lt; MyClass()完全匹配运算符的重载&lt;&lt;和&gt;&gt;,假设你的'myStream&#39;是相应的流类型。完美匹配优先于需要用户定义转换的任何匹配。实际上,以下代码编译对我来说很好。您使用的是哪种编译器?

class MyClass {
public:
    operator std::string();

    friend std::istream& operator>>(std::istream&, const MyClass&);
    friend std::ostream& operator<<(std::ostream&, const MyClass&);
};

void just_do_it()
{
    std::cout << MyClass();
}
相关问题