2017-06-13 98 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