我猜這在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;
}
你能引用確切的錯誤並給出產生它的代碼嗎?因爲這段代碼[編譯對我來說很好](http://coliru.stacked-crooked.com/a/fe235c1b2daa5d96) – Borgleader
爲我編譯g ++ 5.1.0你忘了'#include'嗎? –
您定位哪個標準? 03,11,14,17? –