Answer to Question #32918 in C++ for rakesh mr

Question #32918
can anybody pls post simple examples of overloading comma and o/p operators..
1
Expert's answer
2013-07-09T09:40:17-0400
#include <vector>
//overloaded comma
using std::vector;


template<class _Tp> class Vector
: private vector<_Tp>
{
private:
typedef vector<_Tp> _Base;
typedef Vector<_Tp> _Self;


public:
_Self& operator,(const _Tp& __obj) // comma operator overloading to create a defined function
{ // with an arbitrary number of parameters of the same type(ease of entry)
_Base::push_back(__obj);
return *this;
}
};


void F(const Vector<int>& __obj)
{
//some code
}


//overloaded extraction operator >> and insertion operator <<
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output,
const Distance &D )
{
output << "F : " << D.feet << " I : " << D.inches;
return output;
}


friend istream &operator>>( istream &input, Distance &D )
{
input >> D.feet >> D.inches;
return input;
}
};


int main()
{
//overloaded comma
Vector<int> a;
F((a,1,2,3,4,5,6,7,8,9,10));


//overloaded extraction operator >> and insertion operator <<
Distance D1(11, 10), D2(5, 11), D3;
//Here it is important to make operator overloading function a friend of the class because it would be called without //creating an object.
cout << "Enter the value of object : " << endl;
cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS