2013-07-28 38 views
0

我得到「未解決的外部符號」爲下面的代碼:未解決的外部符號超載

template <int n> class Fibo 
{ 
private: 
    int pre, cur, next, tmp; 
public: 
    Fibo() : pre(1), cur(1), next(2), tmp(0) {} 
    int get() 
    { 
     if(n == 0 || n == 1) return 1; 
     for(int i = 2; i < n; ++i) 
     { 
      next = pre + cur; 
      tmp = cur; 
      cur = next; 
      pre = tmp; 
     } return pre + cur; 
    } 

    friend ostream& operator<< (ostream& out, Fibo<n>& f); 
}; 

template<int n> 
ostream& operator<< (ostream& out, Fibo<n>& f) 
{ 
    out << f.get(); 
    return out; 
} 

int main() 
{ 
    Fibo<5> a; 
    cout << a << endl; 
    cin.get(); 
} 

我得到當我試圖打印a此編譯錯誤:

cout << a << endl; 。當我打印「正常」時,即cout << a.get() << endl,沒有錯誤彈出。

我知道Unresolved external symbols錯誤與未實現的聲明函數關聯。是我的代碼中的情況?我找不到它。

回答

1

有一對夫婦的方式來處理這個問題:

template <int n> class Fibo ; // Forward declaration 

// Definition, you could also forward declare here and define after the class 
template<int n> 
ostream& operator<< (ostream& out, Fibo<n>& f) 
{ 
    out << f.get(); 
    return out; 
} 
template <int n> class Fibo 
{ 
    // Don't forget <> to tell its a template 
    friend ostream& operator<< <> (ostream& out, Fibo<n>& f); 
}; 

上述方法是冗長,但你也可以定義friend一流:

template <int n> class Fibo 
{ 
    // Note this is not a template 
    friend ostream& operator<< (ostream& out, Fibo& f) 
    { 
     out << f.get(); 
     return out; 
    } 

}; 

的一流定義將定義每個實例的功能,即Fibo<1>,Fibo<2>等。

-1

GCC編譯器的消息:

test.C:22:57: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, 
Fibo<n>&)’ declares a non-template function [-Wnon-template-friend] 
test.C:22:57: note: (if this is not what you intended, make sure the function 
template has already been declared and add <> after the function name here) 

不言自明,我認爲。