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;
}
#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