模板和重载操作符<< [英] Templates and overloadering operator <<

查看:163
本文介绍了模板和重载操作符<<的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试重载<<运算符,但编译器给我一个链接器错误。目标是能够将解除引用的基类指针发送到std :: cout,使得导出的运算符<



这可能吗?

  class IBase 
{
public:
IBase(){};
virtual〜IBase(){};
};

template< typename T>
class Derived
:public IBase
{
public:
Derived(T data);
friend std :: ostream& operator<<(std :: ostream& os,const Derived< T>& dt);
private:
T data_;
};

template< typename T>
Derived< T> :: Derived(T data)
:IBase(),
data_(data)
{
}

template< typename T>
std :: ostream& operator<<<(std :: ostream& os,const Derived< T& dt)
{
os< dt.data_;
return os;
}


int _tmain(int argc,_TCHAR * argv [])
{


//问题1
Derived< int> der(234);
std :: cout<< der;

//问题2
// IBase * base = new Derived< int>(5);
// std :: cout<< * base
}

这里有错误:



> >


&,class Derived const&)(?? 6 @ YAAAV?$ basic_ostream @ DU?$ char_traits @ D @ std @@@ std @@ AAV01 @ ABV?$ Derived @ H @@@ Z)



p>


致命错误LNK1120:1未解析的外部





 模板< typename T1> 
friend std :: ostream& operator<<(std :: ostream& os,const Derived< T1>& dt);


I'm trying to overload the << operator for a class template, but the compiler gives me a linker error. The goal is to be able to send a de-referenced base class pointer to std::cout so that the derived operator<< gets called.

Is this possible?

class IBase
{
public:
    IBase() {};
    virtual ~IBase() {};
};

template <typename T>
class Derived
    : public IBase
{
public:
    Derived(T data);
    friend std::ostream& operator<<(std::ostream& os, const Derived<T>& dt);
private:
    T data_;
};

template <typename T>
Derived<T>::Derived(T data)
    : IBase(),
      data_(data)
{
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const Derived<T>& dt)
{
    os << dt.data_;
    return os;
}


int _tmain(int argc, _TCHAR* argv[])
{


    // Question 1
    Derived<int> der(234);
    std::cout << der;

    // Question 2
    //IBase* base = new Derived<int>(5);
    // std::cout << *base
}

Here are the errors:

error LNK2001: unresolved external symbol "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream

&,class Derived const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$Derived@H@@@Z)

and

fatal error LNK1120: 1 unresolved externals

解决方案

You need to declarate friend operator as a template too

template<typename T1>
friend std::ostream& operator<<(std::ostream& os, const Derived<T1>& dt);

这篇关于模板和重载操作符&lt;&lt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆