C++模板,重载运算符<<,参照的C++primer,为什么有编译错误呢?

2019-01-02 19:47发布

问题:

#include<iostream>
using namespace  std;
template<typename T>
class Code;

//友元函数的声明;
template<typename T>
ostream& operator<< (ostream& , Code<T>&);

template<typename T>
class Code
{
public:
    friend ostream& operator << <T>(ostream& out, const Code<T>&code);
    Code() {data=10;}

private:
    T data;
};

//友元函数的实现;
template<typename T>
ostream& operator << (ostream& out, const Code<T>&code)
{
    out << "data: " << code.data << endl;
    return out;
}
int main()
{
    Code<int> d;
    cout<<d<<endl;
    return 0;
}

错误信息:[Error] template-id 'operator<< <int>' for 'std::ostream& operator<<(std::ostream&, const Code<int>&)' does not match any template declaration

回答1:

声明改成const Code&



标签: