开发者

Building generic overloaded operator<<

开发者 https://www.devze.com 2023-03-15 02:24 出处:网络
How can we make a generic overloaded operator<< ? 开发者_高级运维 I wrote this code but clearly it has errors - missing type specifier - int assumed. Note: C++ does not support default-int.

How can we make a generic overloaded operator<< ?

开发者_高级运维

I wrote this code but clearly it has errors - missing type specifier - int assumed. Note: C++ does not support 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();
 }

What can be done here?

Edit: Changed "int i" to a private member

Answer: friend function needs to be declared this way in class a and class b:

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


Put template<class t> into the friend declaration as well.

I wouldn't design operator<< this way, however - why would it need access to private members? Better add a getter for i to both a and b and avoid the socializing stuff altogether.

Edit In the given code the friend declarations would not even be required as i is public in both cases. I based my answer on the presumption that they are intended to be private because otherwise being friends makes no sense here.


What's a t? In the template itself it represents an arbitrary type, but that's after the two uses of it that are causing errors.


If you have a function like

template<class t>
ostream& operator<<(ostream& o, const t& value) 

You must at least put this in the same namespace as the types you want to print. Otherwise, the type t will match all types in the entire program, including all my types that I perhaps don't want to print this way.

It is generally not a good idea to define a template for any t as you risk making it way too general. Ask yourself, will it really work for all ts?

0

精彩评论

暂无评论...
验证码 换一张
取 消