Need a project done?

C++ Programming Developer

Search This Blog

Overload << operator C++

Overload << Operator in C++.

#include <iostream>
using namespace std;

class a{
friend ostream& operator<<(ostream out, a& obj);

int x; //private
public:
int getX(){return x;}
void setX(int a){
x = a;
}
};

ostream& operator << (ostream& out, a& obj){
out << "obj.x = " << obj.x << endl;
return out;
}

int main(){
a obj1, obj2;
obj1.setX(5);//Functions are called over objects.
cout << obj1;
obj2.setX(10);
cout << obj2;
return 0;
}

//If this Code doesn't work in some compiler, use following code:




#include <iostream>
using namespace std;

class a{
friend ostream& operator<<(ostream& out, a& obj){
out << "obj.x = " << obj.x << endl;
return out;
}
 int x; //private
public:
 int getX(){return x;}
 void setX(int a){
  x = a;
 }
};


int main(){
 a obj1, obj2;
 obj1.setX(5);//Functions are called over objects.
 cout << obj1;
 obj2.setX(10);
 cout << obj2;
 return 0;
}

No comments:

Post a Comment

"Don't let anyone ever make you feel like you don't deserve what you want."