Overloading ">>" and "<<" in C++ [duplicate] - c++

This question already has answers here:
What are the basic rules and idioms for operator overloading?
(8 answers)
Closed 9 years ago.
Look at my code below. I made a class Vector2D. I overloaded the + operator and the * operator. In the main function I test these 2 overloaded operators. The only thing I want to add to this is the following: I want to overload the >> operator(?) so when I use >>, I can type in a vector. (so the x and the y component). Then I want to overload the << operator(?) so when I use <<, the program will return me my inputted vector.
#include <iostream>
using namespace std;
class Vector2D
{
public:
Vector2D();
Vector2D(double X = 0, double Y = 0)
{
x = X;
y = Y;
};
double x, y;
Vector2D operator+(const Vector2D &vect) const
{
return Vector2D(x + vect.x, y + vect.y);
}
double operator*(const Vector2D &vect) const
{
return (x * vect.x) + (y * vect.y);
}
};
int main()
{
cout << "Adding vector [10,10] by vector [5,5]" << endl;
Vector2D vec1(10, 10);
Vector2D vec2(5, 5);
Vector2D vec3 = vec1 + vec2;
cout << "Vector = " << "[" << vec3.x << "," << vec3.y << "]" << endl;
cout << "Dot product of vectors [5,5] and [10,10]:" << endl;
double dotp = vec1 * vec2;
cout << "Dot product: " << dotp << endl;
return 0;
}
The only problem is, I dont know how to do this. Could someone help me^.^?? Thanks in advance.

You need to declare these as friend functions to your Vector2D class (these may not meet your exact need and may require some formatting tweaking):
std::ostream& operator<<(std::ostream& os, const Vector2D& vec)
{
os << "[" << vec.x << "," << vec.y << "]";
return os;
}
std::istream& operator>>(std::istream& is, Vector2D& vec)
{
is >> vec.x >> vec.y;
return is;
}

Related

How to print two coordinates from class?

I have been trying to print the points like The position of the point is (1,2) from using class, but I can't figure out a way to do it. I simply can't find a way to return two numbers like that, but the problem requires solution that way.
#include <iostream>
using namespace std;
class MyPoint{
public:
int x,y,radius;
MyPoint()
{
x=0;
y=0;
}
MyPoint(int x1,int y1)
{
x=x1;
y=y1;
}
int point_display()
{
char st=(x,y);
return st;
}
int getAdd()
{
return x+y;
}
};
int main()
{
MyPoint mypoint;
cin>>mypoint.x>>mypoint.y;
cout<<"The position of the point is "<<mypoint.point_display()<<endl;
cout<<"The sum of the coordinates is "<<mypoint.getAdd()<<endl;
return 0;
}
The usual solution to this is to provide an overload of operator << for class MyPoint to print the point.
Something like this:
#include <iostream>
using namespace std;
class MyPoint{
public:
int x,y,radius;
MyPoint()
{
x=0;
y=0;
}
MyPoint(int x1,int y1)
{
x=x1;
y=y1;
}
int getAdd()
{
return x+y;
}
friend ostream& operator << (ostream& os, const MyPoint& p);
};
ostream& operator << (ostream& os, const MyPoint& p)
{
os << p.x << ", " << p.y;
return os;
}
int main()
{
MyPoint mypoint { 1,2 };
cout<<"The position of the point is "<<mypoint<<endl;
cout<<"The sum of the coordinates is "<<mypoint.getAdd()<<endl;
return 0;
}
Output:
The position of the point is 1, 2
The sum of the coordinates is 3
Live demo
Your point_display could return a string composed of the 2 values:
std::string point_display()
{
return std::string{"("} + std::to_string(x)
+ "," + std::to_string(x) + ")";
}
Alternatively, as your question asks about returning 2 values, the function could return a pair:
std::pair<int,int> point_display ()
{
return {x,y};
}
and in main, you could do:
auto [x, y] = mypoint.point_display();
cout << "The position of the point is ("
<< x << "," << y << ")" << endl;
However, since the data members are public, you could just destructure the object and print out the values in main:
auto [x, y, radius] = mypoint;
cout << "The position of the point is ("
<< x << "," << y << ")" << endl;
If all you want to do is print the coordinates, you could have the method do it:
void point_display()
{
cout << "(" << x << ", " << y << ")";
}
...
cout<<"The position of the point is ";
mypoint.point_display();
cout << endl;
If you really want to return the coordinates, you could have separate accessors ("getters"):
int getX()
{
return x;
}
int getY()
{
return y;
}
or use references:
void getCoordinates(int &rx, int &ry)
{
rx = x;
ry = y;
}
...
int a, b;
mypoint.getCoordinates(a, b);
cout << a << " " << b << endl;

How does operator overloading work, and why doesn't it work in my case?

I've been provided a driver function that is supposed to demonstrate the results of operator overloading involving complex numbers. After reading up on overloading a while I managed to write the code in a way that it successfully compiles, however somewhere along the way the correct values are not being outputted by the program.
From what I understand overloading essentially works like a function. Objects are passed and the "function" can then do arithmetic/whatever with it and return a new object. Where I'm slightly lost though, is how overloading knows what values are being passed. For example, in my case I overloaded the "+" and "=" operators in order to add two complex numbers in the form "x = y + z". When the compiler comes across the "=" symbol, I'm assuming it simply passes whatever is on both the left and right side and passes those? Same with "+". In this case it would be passing "y" since it's the object on the left and "z" because it's the object on the right?
Here's my current "complex" class which includes the overloading definitions.
class Complex {
private:
double realPart;
double imaginaryPart;
public:
// friends
friend ostream & operator<<(ostream &out, const Complex &c);
friend istream & operator>>(istream &in, Complex &c);
// constructors
Complex()
{
realPart = 0;
imaginaryPart = 0;
}
Complex(double real)
{
realPart = real;
imaginaryPart = 0;
}
Complex(double real, double imaginary)
{
realPart = real;
imaginaryPart = imaginary;
}
// end of constructors
// + overloading
Complex operator+(Complex const &c)
{
Complex Add;
Add.realPart = realPart + c.realPart;
Add.imaginaryPart = imaginaryPart + c.imaginaryPart;
return Add;
}
// - overloading
Complex operator-(Complex const &c)
{
Complex Subtract;
Subtract.realPart = realPart - c.realPart;
Subtract.imaginaryPart = imaginaryPart - c.imaginaryPart;
return Subtract;
}
// * overloading
Complex operator*(Complex const &c)
{
Complex Multiply;
Multiply.realPart = (realPart * c.realPart) - (imaginaryPart * c.imaginaryPart);
Multiply.imaginaryPart = (realPart * c.imaginaryPart) - (imaginaryPart * c.realPart);
return Multiply;
}
// = overloading
Complex operator=(Complex const &c)
{
Complex Assignment;
Assignment.realPart = realPart;
Assignment.imaginaryPart = imaginaryPart;
return Assignment;
}
// == overloading
bool operator==(Complex const &c)
{
Complex Compare;
if (Compare.realPart == realPart && Compare.imaginaryPart == imaginaryPart)
{
return true;
}
else
{
return false;
}
}
// != overloading
bool operator!=(Complex const &c)
{
Complex NotEqual;
if (NotEqual.realPart == realPart && NotEqual.imaginaryPart == imaginaryPart)
{
return false;
}
else
{
return true;
}
}
};
// << overloading
ostream& operator<<(ostream& out, const Complex &c)
{
out << c.realPart;
if (c.imaginaryPart >= 0)
{
out << " + " << c.imaginaryPart << "i" << endl;
}
else
{
out << " - " << fabs (c.imaginaryPart) << "i" << endl;
}
return out;
}
// >> overloading
istream& operator>>(istream &in, Complex &c)
{
in >> c.realPart;
in >> c.imaginaryPart;
return in;
}
And here's the driver program:
int main()
{
for (double i = 1; i < 10; ++ i)
{
Complex y{i * 2.7, i + 3.2};
Complex z{i * 6, i + 8.3};
Complex x;
Complex k;
std::cout << "Enter a complex number in the form: (a, b)\n? ";
std::cin >> k; // demonstrating overloaded >>
std::cout << "x: " << x << "\ny: " << y << "\nz: " << z << "\nk: " << k << '\n'; // demonstrating overloaded <<
x = y + z; // demonstrating overloaded + and =
std::cout << "\nx = y + z:\n" << x << " = " << y << " + " << z << '\n';
x = y - z; // demonstrating overloaded - and =
std::cout << "\nx = y - z:\n" << x << " = " << y << " - " << z << '\n';
x = y * z; // demonstrating overloaded * and =
std::cout << "\nx = y * z:\n" << x << " = " << y << " * " << z << "\n\n";
if (x != k)
{ // demonstrating overloaded !=
std::cout << x << " != " << k << '\n';
}
std::cout << '\n';
x = k;
if (x == k)
{
// demonstrating overloaded ==
std::cout << x << " == " << k << '\n';
}
std::cout << std::endl;
}
}
Upon running, the problem seems to be with the object "x". Entering "5 2" will still output "x: 0 + 0i" This leads me to believe the issue is with either overloading of "=" or the stream operators. That said, I can't quite figure out why nothing is happening.
Is there an error in how I've constructed the "=" overloading definition as I think, or is it maybe something bigger I'm missing?
Your = is wrong; it should return *this.
Complex& operator=(Complex const &c)
{
realPart = c.realPart;
imaginaryPart = c.imaginaryPart;
return *this;
}
Fix that and most of the rest looks sane.
The operator=() is not correct: user Yakk - Adam has already shown you how to fix it. To give you insight on why it is wrong and what return *this does; let's look at your original function:
Complex operator=(Complex const &c) {
Complex Assignment;
Assignment.realPart = realPart;
Assignment.imaginaryPart = imaginaryPart;
return Assignment;
}
Here your signature takes a const reference to another Complex object this part is correct. Your return type is a Complex object this is in essence wrong because you don't want to return a copy of an object. The objective here is to perform assignment. This means you must make changes to the original LHS instance.
In the expression A = B + C; A is considered the LHS instance. Here you want to assign the expression (B + C) which are both RHS values.
So when Yakk - Adam showed you how to fix this by:
Complex& operator=(Complex const &c) {
realPart = c.realPart;
imaginaryPart = c.imaginaryPart;
return *this;
}
One of the differences here is that the return type is now a Reference to a specific object instead of a copy to an object.
Another difference is that there is no need to create a local temporary copy as you did in your original version:
Complex Assignment; // this is not needed
By removing that from operator=() he simply replaced these lines of code:
// Assignment.realPart = realPart; // To
realPart = c.realPart;
// Assignment.imaginaryPart = imaginaryPart; // To
imaginaryPart = c.imaginaryPart;
Here you are using the class's members directly and assigning to them the value that belongs to the other or c that is passed to the operator.
Then finally to return your LHS instance with the updated value; this is where you have to return a dereferenced this pointer.
What does *this mean? The this pointer is a special pointer that belongs to all class and struct types. For example any time you have class object:
class Foo {
public:
int bar { 10 };
void addFive();
};
You can use the this pointer directly in your member functions:
void Foo::addFive() {
this->bar += 5; // same as below (this) belongs to this particular instance.
// bar += 5;
}
Regarding your operator=(); since you are returning by reference you can not simply just return this. This will return the this pointer. We don't want a pointer to the object as we want a reference to the object; so we must deference the this pointer by returning *this.
I hope this helps clear things up for you.

c++ how to access STL complex + binary operator

Hello I have trouble access STL complex + binary operator, my fVector is derived from std::complex, I try to call the std::complex binary + operator function to do the calculation, but I say it does have member of operator +.
ok update more of my code as request, there is 3 file which is fVector2D_test.cpp fVector2D.cpp and fVector2D.hpp
#include <iostream>
#include <complex>
#include "fVector2D.hpp"
//using namespace std;
using std::cout;
using std::endl;
int main()
{
/*fVector2D u, v(2.4f, 7), w(v);
cout << v.X(); u = fVector2D(u.X(), v.Y());
cout << u <<endl;
// v.Y() = 3.4f; // compiler error
fVector2D a(1, 2), b(2, 3);
float dot = a*b;
cout << dot <<endl;
cout << fVector2D::EX << "+" << fVector2D::EY;*/
fVector2D v(3,4.1f), u(1.2f,8.5f);
fVector2D w = u + v;
cout << w << endl;
//w = exp(std::complex<float>(0,0.2f))*v;
//cout << w << endl;
// cout << (u*v) << endl;
//cout << fVector2D::EX << endl;
//cout << fVector2D::EY << endl;
//cout << abs(v) << endl;
return 0;
}
#include <complex>
class fVector2D : public std::complex<float>
{
public:
fVector2D(float x=0, float y =0);
fVector2D(const fVector2D& floatVector2D);
float X()const;
float Y()const;
//static const EX;
//static const EY;
private:
};
fVector2D operator+(const fVector2D& , const fVector2D&);
#include "fVector2D.hpp"
fVector2D::fVector2D(float x, float y)
: std::complex<float>(x, y)
{
}
fVector2D::fVector2D(const fVector2D& floatVector2D)
: std::complex<float>(floatVector2D)
{
}
float fVector2D::X()const
{
return real();
}
float fVector2D::Y()const
{
return imag();
}
fVector2D operator+(const fVector2D& lhs, const fVector2D& rhs)
{
return std::complex<float>::operator+(lhs,rhs);// compile error , no operator + in the member
}
+ for complex numbers is a free function, not a member function. That is why you can not access it using complex<float>:: syntax.
Beside this problem your code has other problems(I have trouble seeing any real scenario where one would want to inherit from std::complex), but that is outside the scope of the question.

How do I simply print a vector?

If I have a vector like this:
struct vector3D {
float x;
float y;
float z;
};
vector3D aVector = { 3.4, 4.4, 9.3 }; // my vector
How can I cout the aVector to the console?
you can overload the insertion operator << to use for your objects:
struct vector3D {
float x;
float y;
float z;
friend ostream& operator<<(ostream& out, vector3D rhs){
out << "( " << rhs.x << ", " << rhs.y << ", " << rhs.z << " )" << endl;
return out;
}
};
now you can use cout to print your object values:
int main(){
vector3D v = {10, 20, 30};
cout << v << endl;
}

How to display coordinates from class?

I am having issues displaying coordinates that are read into a class. This is my first time using classes so please be understanding!
Here is what I have so far:
#include <iostream>
using namespace std;
class Vector{
private:
float x;
float y;
public:
Vector(float f1, float f2)
{
x=f1;
y=f2;
}
Vector(){}
float display()
{
Vector v;
cout << "(" << v.x << "," << v.y << ")" << endl;
return 0;
}
};
int main()
{
Vector v1(0.5, 0.5);
cout << "v1 ";
v1.display();
system("pause");
return 0;
}
It prints
v1 (-1.07374e+008,-1.07374e+008)
Your problem is that you are not printing out the coordinates of the Vector you created in main() but a default created one in your function. Instead of
float display()
{
Vector v;
cout << "(" << v.x << "," << v.y << ")" << endl;
return 0;
}
You need
float display()
{
//Vector v; remove this
cout << "(" << x << "," << y << ")" << endl;
// no v.x no v.y
return 0;
}
I suggest you change the default constructor to
Vector() : x(0), y(0) {}
So it would have printed
v1 (0,0)
You should also change
Vector(float f1, float f2)
{
x=f1;
y=f2;
}
To
Vector(float f1, float f2) : x(f1), y(f2) {}
As it is a good habit to get into. This can save resources and CPU cycles when dealing with non POD types. For more information see Why should I prefer to use member initialization list?
the Vector v; line is a mistake. You are basically creating a new uninitialized vector instead of crating your own instance.
one correction would be:
int display()
{
cout << "(" << x << "," << y << ")" << endl;
return 0;
}
since x and y are member of this class