cout运算符重载的未解析外部符号

时间:2013-07-28 20:34:00

标签: c++ visual-studio-2010

我收到以下代码的“未解析的外部符号”:

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错误与未实现的声明函数相关联。是我的代码中的情况?我找不到了。

2 个答案:

答案 0 :(得分: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>等。

答案 1 :(得分:-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) 

我认为这是不言自明的。