首页 文章

C重载运算符<<在模板类中[重复]

提问于
浏览
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错误LNK1120:2个未解析的外部


我的代码出了什么问题?

4 回答

  • 1

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

    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>&);
    
  • 1

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

  • 4

    编辑我现在看到问题已经更新,构造函数已经定义 .

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

    那么你宣布构造函数

    mytype(T);
    

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

    编译器不会为上面的构造函数创建默认主体,因为它不知道如何操作 .

  • 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的构造函数 . 对于模板类,您应该在类中实现所有方法(和构造函数等) .

相关问题