构建通用重载运算符<<

时间:2011-06-24 21:25:36

标签: c++ templates

我们如何制作通用重载运算符<< ?

我编写了这段代码,但很明显它有错误 - 缺少类型说明符 - 假设为int。注意:C ++不支持default-int。

class b{
private:
    int i;
public:
    b(){}
    b(const int& ii):i(ii){}
    friend ostream& operator<<(ostream& o,const t& obj);//Error here
};


class a:public b{
private:
    int i;
    int x;
public:
    a(){}
    a(const int& ii,const int& xx):i(ii),x(xx){}
    friend ostream& operator<<(ostream& o,const t& obj);//Error here
};

template<class t>
ostream& operator<<(ostream& o,const t& obj){
         o<<obj.i;
         return o;
}

int main()
 {
    b b1(9); 
    a a1(8,6);
    cout<<a1<<endl<<b1;
    _getch();
 }

这里可以做些什么?

编辑:将“int i”更改为私人会员

答案: friend函数需要在类a和类b中以这种方式声明:

template<class t>
    friend ostream& operator<< <>(ostream& o,const t& obj);

3 个答案:

答案 0 :(得分:2)

template<class t>放入friend声明中。

我不会这样设计operator<<,但为什么需要访问私人会员?最好为ia添加b的getter,并完全避免社交内容。

修改在给定代码中,甚至不需要friend声明,因为ipublic中都是private。我的答案基于这样一种假设,即它们的目的是{{1}},因为在这里做朋友是没有意义的。

答案 1 :(得分:1)

什么是t?在模板本身中,它表示一种任意类型,但是在两次使用它之后会导致错误。

答案 2 :(得分:0)

如果你有像

这样的功能
template<class t>
ostream& operator<<(ostream& o, const t& value) 

您必须至少将其放在与要打印的类型相同的命名空间中。否则,类型t将匹配整个程序中的所有类型,包括我可能不希望以这种方式打印的所有类型。

为任何t定义模板通常不是一个好主意,因为您可能会过于笼统。问问自己,它是否真的适用于所有 t

相关问题