3

可能重复:
为模板类重载友元运算符<<

我正在尝试为模板类重载 operator<<,但出现错误...


最终(固定)代码:

template<class T>
class mytype
{
    T atr;
public:
    mytype();
    mytype(T);
    mytype(mytype&);
    T getAtr() const;
    T& operator=(const T&);
    template<class U> friend ostream& operator<<(ostream&,const mytype<U>&);
};

template<class T>
mytype<T>::mytype()
{
    atr=0;
}

template<class T>
mytype<T>::mytype(T value)
{
    atr=value;
}

template<class T>
mytype<T>::mytype(mytype& obj)
{
    atr=obj.getAtr();
}


template<class T>
T mytype<T>::getAtr() const
{
    return atr;
}

template<class T>
T& mytype<T>::operator=(const T &other)
{
    atr=other.getAtr();
    return *this;
}

template<class U>
ostream& operator<<(ostream& out,const mytype<U> &obj)
{
    out<<obj.getAtr();
    return out;
}

(全部在头文件中)


VS2012 错误:

1)

错误 1 ​​错误 LNK2019:函数 _wmain 中引用的未解析外部符号“public: __thiscall mytype::mytype(int)”(??0?$mytype@H@@QAE@H@Z)

2)

错误 2 错误 LNK2019: 无法解析的外部符号 "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream > &,class mytype const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@ D@std@@@std@@AAV01@ABV?$mytype@H@@@Z) 在函数 _wmain 中引用

3)

错误 3 error LNK1120: 2 unresolved externals


我的代码有什么问题?

4

4 回答 4

4

你告诉编译器期待一个免费的非模板函数:

friend ostream& operator<<(ostream&,const mytype<T>&);

...但随后您定义了一个函数模板:

template<class T>
ostream& operator<<(ostream& out,const mytype<T> &obj)
{
    out<<obj.getAtr();
    return out;
}

告诉编译器期待一个函数模板:

template<class T> friend ostream& operator<<(ostream&,const mytype<T>&);
于 2012-11-26T18:24:01.903 回答
1

似乎缺少构造函数的实现/定义。

于 2012-11-26T18:21:12.270 回答
1

编辑我现在看到问题已经更新并且构造函数已经定义。

在这种情况下,您只需将构造函数定义放在标题中。有些人这样做的另一种方法是定义一个 .inl(inline) 文件并将其包含在标题的底部。

那么你声明构造函数

mytype(T);

但是你从来没有真正开始定义它。

编译器不会为上述构造函数创建默认主体,因为它不知道如何去做。

于 2012-11-26T18:23:21.547 回答
1

您还需要template<class T>在类的声明中指定运算符:

template<class T>
class mytype
{
    T atr;
public:
    ...
    T getAtr() const;

    template<class U>
    friend ostream& operator<<(ostream&,const mytype<U>&);
    ...
};

或者,在类中实现运算符:

template<class T>
class mytype
{
    T atr;
public:
    ...
    T getAtr() const;

    friend ostream& operator<<(ostream&,const mytype<T>&)
    {
        ...
    }

    ...
};

至于第一个错误,可能是因为你在源文件中实现了mytype的构造函数。对于模板类,您应该在类中实现所有方法(和构造函数等)。

于 2012-11-26T18:24:21.100 回答