将union作为参数传递给运算符<<

时间:2017-06-13 20:07:12

标签: c++

我试图在下面的琐碎代码中找出错误:

union YunYun
{   
    int i;

    YunYun() : i(99) {}

    friend std::ostream& operator<<(std::ostream &os, const YunYun &y)
    {   
        os << y.i;
        return os; 
    }   
};  

int main()
{
    YunYun yn;

    std::cout << yn << std::endl; //This will not execute.

    return 0;
}

如果重载operator<<是我的联盟的朋友或成员函数,编译器会给我一个错误,但如果它是正常函数,它就可以正常工作。

任何想法,可能导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:1)

我猜你在MS Visual C ++中失败了吗?

将函数定义移出联合:

union YunYun
{
    int i;

    YunYun() : i(99) {}

    friend std::ostream& operator<<(std::ostream& os, const YunYun& y);        
};

std::ostream& operator<<(std::ostream& os, const YunYun& y)
{
    os << y.i;
    return os;
}

int main()
{
    YunYun yn;

    std::cout<< yn <<std::endl; //This will not execute.

    return 0;
}

即使定义在联合之外,联合中的友元声明也会导致运算符&lt;&lt;成为朋友它似乎是Visual C ++中的一个错误导致这一点。

再往前看,似乎有一些奇怪的规则可以将朋友功能暴露给外部范围。

union YunYun
{
    int i;    
    YunYun() : i(99) {}

    friend std::ostream& operator<<(std::ostream& os, const YunYun& y)
    {
        os << y.i;        
        return os;
    }

    friend void foo()
    {
        std::cout << "foo" << std::endl;
    }

    friend void bar(const YunYun& y)
    {
        std::cout << "bar " << y.i << std::endl;
    }
};

// without something declared outside the union scope VC++ won't find this symbol
std::ostream& operator<<(std::ostream& os, const YunYun& y);

int main()
{
    YunYun yn;
    std::cout << yn << std::endl; //This will not execute in VC++ w/o declaration external to union scope
    // foo(); // error: undeclared identifier (in VC++/Clang/GCC)
    bar(yn); // works in all three compilers

    return 0;
}