2017-06-13 99 views
0

我想在我的下面琐碎的代码找出错误:错误传递工会作为参数的操作符<<

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

你能引用确切的错误并给出产生它的代码吗?因为这段代码[编译对我来说很好](http://coliru.stacked-crooked.com/a/fe235c1b2daa5d96) – Borgleader

+1

为我编译g ++ 5.1.0你忘了'#include '吗? –

+0

您定位哪个标准? 03,11,14,17? –

回答

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; 
} 

即使定义是工会之外,工会里面的朋友声明将使运营商< <成为朋友。它似乎是导致此问题的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; 
} 
+0

从问题:*但如果它是一个正常的功能,它工作得很好。任何想法,什么可能会导致这个错误?*在我看来,你告诉OP他们已经知道什么,而不是实际回答这个问题(为什么会发生这种情况/是什么原因造成的) – Borgleader

+0

这似乎是VC++中的一个编译器错误。如果我用'struct'或'class'替换'union',它可以很好地工作。请参阅https://stackoverflow.com/questions/1115464/msvc-union-vs-class-struct-with-inline-friend-operators – benf