0

I'm getting "Unresolved external symbols" for the following code:

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

I get this compilation error when I'm trying to print a:

cout << a << endl;. When I'm printing "normaly", i.e. cout << a.get() << endl, no errors popped.

I know that Unresolved external symbols error are associated with declared function that didn't implemented. is that the case in my code? I can't find it.

4

2 回答 2

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

};

类内定义将为friend每个实例定义一个函数,即Fibo<1>,Fibo<2>等。

于 2013-07-28T20:55:36.137 回答
-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) 

我认为非常不言自明。

于 2013-07-28T20:45:55.333 回答