2013-02-25 88 views
0

當我嘗試編譯此(G ++):嵌套類的朋友操作模板類,編譯出錯

template<typename T> 
struct A { 

    struct B { }; 

    template<typename S> 
    friend A<S>& operator +(A<S> const &, A<S> const &); 
}; 

template<typename T> 
A<T>& operator +(A<T> const &a, A<T> const &b) { 
    A<T>::B *x; 
    return a; 
} 

main() { } 

我得到

test.cpp: In function "A<T>& operator+(const A<T>&, const A<T>&)": 
test.cpp:12:11: error: "x" was not declared in this scope 

爲什麼?

[忽視:如果我不包括這一行,堆棧溢出說我必須在我的崗位太多的代碼,當我保存]

+3

'B'取決於類型,使用'TYPENAME甲 :: B * X;'參見http://stackoverflow.com/questions/610245/where-and-why-do-i -have-to-put-the-template-and-typename-keywords – hmjd 2013-02-25 09:43:18

+0

'main(){} A'?這不是有效的C++。 – 2013-02-25 09:43:46

+0

並且您在聲明中使用了'S',在'operator +'的定義中使用了'T' – 2013-02-25 09:43:53

回答

2

編譯器不知道A<T>::B表示類型,因此它會嘗試在那裏做乘法。

使用typename A<T>::B *x;

+0

感謝您的修復和獎金解釋。 – 2013-02-25 10:05:16