Friend function must use

code:
#include<iostream>
using namespace std;
class complex{
private:
    int a,b;
public:
    complex(){a=0,b=0;}
    complex(int a,int b){
        this->a=a;
        this->b=b;
    }
    void show(){
        cout<<a<<'+'<<b<<'i'<<endl;
    }
    friend void operator<<(ostream&,complex);
};

void operator<<(ostream &bout,complex C){
    cout<<"In overloaded operator"<<endl;
    cout<<C.a<<'+'<<C.b<<'i';
}
int main()
{
    complex com1(2,5),com2(3,7);
    com1.show();
    cout<<com1;
    cout<<com2;
    return 0;

}



If we want to print more than one value than we have return ostream object. But we never create an ostream object so we make a reference variable.

Code:

#include<iostream>
using namespace std;
class complex{
private:
    int a,b;
public:
    complex(){a=0,b=0;}
    complex(int a,int b){
        this->a=a;
        this->b=b;
    }
    void show(){
        cout<<a<<'+'<<b<<'i'<<endl;
    }
    friend ostream& operator<<(ostream&,complex);
};
ostream& operator<<(ostream &bout,complex C){
    cout<<C.a<<'+'<<C.b<<'i';
    return bout;
}
int main()
{
    complex com1(2,5),com2(3,7);
    com1.show();
    cout<<"Over load output"<<endl;
    cout<<com1<<"  "<<com2<<endl;
    return 0;
}




মন্তব্যসমূহ

এই ব্লগটি থেকে জনপ্রিয় পোস্টগুলি

Big Big mod

শিরোনামহীন গল্প

Dictionaries and Maps