朋友重载运算符没有命名空间std

时间:2013-02-27 18:12:27

标签: c++ namespaces std friend extraction

只是想知道是否有人能指出我正确的方向。我有一个朋友提取运算符,如果我包含命名空间std,它可以工作;但如果我不这样做就会失败。任何人都可以给我一个暗示吗?

ostream& operator << (ostream &out, coins &value)

这也是一个朋友功能,所以我在我的class.h文件中有这个(作为朋友) 在我的functions.h文件中(作为原型)和在我的functions.cpp文件中(逻辑)。

我试过制作它

的std :: ostream的&安培;运营商.... 的std :: ostream的和放; operator std ::&lt;&lt; (等)

但我不知道我哪里出错了。我的编译器一直告诉我'ostream没有命名类型'

谢谢

1 个答案:

答案 0 :(得分:1)

ostream命名空间中存在std,不执行std::<<(甚至没有意义!)。尝试采用较少的霰弹枪编程方法;也就是说,不要只是尝试随机的东西,直到它工作。该错误告诉您ostream(不合格)是问题所在,因此您必须先解决该问题。

#include <iostream>

struct coins
{
    friend std::ostream& operator<<(std::ostream& sink, const coins& value);
};

std::ostream& operator<<(std::ostream& sink, const coins& value)
{
    sink << "doing coins output";
    return sink;
}

int main()
{
    coins c;
    std::cout << c << std::endl;
}

顺便说一下,当您将数据插入流时,这是一个插入运算符。提取将是>>