Overloading Multiplication Operator - c++

I am working on an assignment for my c++ class. We are having to overload several operators such as +, -, !=, =, etc. Well, I have all of them figured out except the multiplication. Everything I have tried gives an overflow or just doesn't compile. Not sure what I need for it.
Here is the header file that holds my overloads.
#ifndef COMPLEXNUMBER_H
#define COMPLEXNUMBER_H
#include<iostream>
using namespace std;
class ComplexNumber{
public:
double real, imaginary;
ComplexNumber(){
real = 0;
imaginary = 0;
}
ComplexNumber(double a, double b){
real = a;
imaginary = b;
}
ComplexNumber(double a){
real = a;
imaginary = 0;
}
ComplexNumber & operator= (const ComplexNumber & rhs){
if(this == &rhs){
return *this;
}
else{
real = rhs.imaginary;
imaginary = rhs.imaginary;
}
return *this;
}
ComplexNumber & operator+= (const ComplexNumber &rhs){
real += rhs.real;
imaginary += rhs.imaginary;
return *this;
}
ComplexNumber & operator-= (const ComplexNumber &rhs){
real -= rhs.real;
imaginary -= rhs.imaginary;
return *this;
}
const ComplexNumber operator+ (const ComplexNumber &rhs){
ComplexNumber result = *this;
result += rhs;
return result;
}
const ComplexNumber operator- (const ComplexNumber &rhs){
ComplexNumber result = *this;
result -= rhs;
return result;
}
const ComplexNumber operator* (const ComplexNumber &rhs){
return *this * rhs;
}
friend ostream & operator<< (ostream &out, const ComplexNumber &c){
out << "(" << c.real << (c.imaginary<0?" - ":" + ") << abs(c.imaginary) << " i)";
return out;
}
friend istream & operator>> (istream & in, ComplexNumber &c){
in >> c.real >> c.imaginary;
return in;
}
operator double(){
return real;
}
bool operator== (const ComplexNumber & rhs) const {
bool result = (this->real == rhs.real) && (this->imaginary == rhs.imaginary);
return result;
}
bool operator!= (const ComplexNumber &rhs) const{
return !(*this == rhs);
}
};
#endif
I know that multiplication operator is way off, but its just what I have at the moment. Here it is on its own. Any ideas would be greatly appreciated!!
const ComplexNumber operator* (const ComplexNumber &rhs){
return *this * rhs;
}

It gives you an overflow because of the way you call it. With your call, you are multiplying a complex number with a complex number, and it just keeps calling the same operator without doing anything. You could try to use some basic math and derive the formula for complex number multiplication. Specifically, let's say we have two complex numbers Z1 and Z2. Let Z1 = a + bi, where a is the real part, and b is the imaginary part, and Z2 = c + di, where c is the real part, and d is the imaginary part. We have Z1 * Z2 = (a + bi)(c + di) = ( ac + adi + cbi - bd ). Now, we separate the real and the imaginary part, the real part here is everything without i, so ac - bd, and the imaginary part would be ad + cb. Now, use that in the terms of your class members, and you would get something like this:
const ComplexNumber operator* (const ComplexNumber &rhs)
{
ComplexNumber result;
result.real = real * rhs.real - imaginary * rhs.imaginary;
result.imaginary = real * rhs.imaginary + imaginary * rhs.real;
return result;
}

Related

Why does my C++ iostream overload failed when called in more complex cin and cout?

Having trouble with the overloaded IOstream in my C++ class, the code below is my header file, so there is no main(). The overloaded iostream seems to work with simple cin and cout calls, but when put into more complex ones, it throws no match for operato<< and operator>>.
/*
Provide three constructors Complex(a, b), Complex(a), and Complex(). Complex()
creates a Complex object for number 0 and Complex(a) creates a Complex object with 0 for b.
Also provide the getRealPart() and getImaginaryPart() functions for returning
the real and imaginary part of the complex number, respectively.
*/
/*
Overload the operators +, -, *, /, +=, -=, *=, /=, [ ], unary + and -, prefix ++ and --,
postfix ++ and --, <<, >>. Overload the operators +, -, *, / as nonmember functions.
*/
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
class Complex{
public:
Complex();
Complex(double a);
Complex(double a, double b);
void set_I(double input);
void set_R(double input);
double get_I_comp() const; //I accessor
double get_R_comp() const; // double accessor
double getRealPart();
double getImaginaryPart();
Complex operator+(Complex other);
Complex operator+(double other);
Complex operator-(Complex other);
Complex operator-(double other);
Complex operator*(Complex other);
Complex operator*(double other);
Complex operator/(Complex other);
Complex operator/(double other);
void operator++();
Complex& operator++(int dummy);
void operator+=(Complex other);
void operator+=(double other);
void operator-=(Complex other);
void operator-=(double other);
void operator*=(double other);
void operator*=(const Complex& other);
void operator/=(double other);
void operator/=(const Complex& other);
void operator- ();
void operator+ ();
double& operator[](int index);
Complex& operator<<(const int& intput);
Complex& operator>>(const string& output);
friend ostream& operator<<(ostream& out, Complex& target);
friend istream& operator>>(const istream& input, Complex& target);
std::string toString() //temporary solution right now
{
if (this->c_I != 0){
string ret = std::to_string(c_R);
ret = ret + " + ";
ret = ret + std::to_string(c_I);
ret = ret + " i \n";
return ret;
}
else{
string ret = std::to_string(c_R);
return ret;
}
}
Complex& add(double num);
Complex& add(Complex other);
Complex& subtract(double num);
Complex& subtract(Complex other);
Complex& multiply(double num);
Complex& multiply(Complex other);
Complex& divide(double num);
Complex& divide(Complex other);
Complex& abs();
private:
double c_I;
double c_R;
};
Complex::Complex() : c_I(0),c_R(0){ //works
}
Complex::Complex(double a) :c_I(0),c_R(a){ //works
}
Complex::Complex(double a, double b){ //works // at first I have the i as a and r as b, so thats why is fliped
this->c_I = b;
this->c_R = a;
}
double Complex::get_I_comp() const{
return c_I;
}
double Complex::get_R_comp() const{
return c_R;
}
double Complex::getImaginaryPart(){
return c_I;
}
double Complex::getRealPart(){
return c_R;
}
void Complex::set_I(double input){
c_I = input;
}
void Complex::set_R(double input){
c_R = input;
}
Complex Complex::operator+(Complex other){
Complex ret( (this->c_R + other.get_R_comp() ),(this->c_I + other.get_I_comp()));
return (ret);
}
Complex Complex::operator+(double other){
Complex ret(this->c_R + other,this->c_I);
return ret;
}
Complex Complex::operator-(Complex other){
Complex ret(this->c_R - other.get_R_comp(),this->c_I - other.get_I_comp());
return ret;
}
Complex Complex::operator-(double other){
Complex ret(this->c_R - other,this->c_I);
return ret;
}
Complex Complex::operator*(double other){
Complex ret(this->c_R * other ,this->c_I *other);
return ret;
}
Complex Complex::operator*(Complex other){
if((other.get_I_comp() != 0) && (other.get_R_comp() != 0) ){
Complex ret = other * (this->c_R);
Complex neu(-(other.get_I_comp()*this->c_I),other.get_R_comp()*this->c_I);
return (ret + neu);
}
if((other.get_I_comp() == 0 ) && (other.get_R_comp() != 0)){
Complex ret(this->c_R,this->c_I);
ret = ret * other.get_R_comp();
return ret;
}
else{
Complex ret((-((this->c_I)*other.get_I_comp())),(this->c_R)*other.get_I_comp());
return ret;
}
}
Complex Complex::operator/(double other){
if (other == 0) { // zero division error handler
throw runtime_error("Math error: Can't div by zero\n");
return 1;
}
if(other != 0){
Complex ret(this->c_R/other,this->c_I/other);
return ret;
}
}
//To divide a+bi by c+id we will perform the operation (ac+bd)/(c^2 + d^2) + (bc-ad)/(c^2 + d^2)i.
Complex Complex::operator/(Complex other){
if ((other.get_I_comp() != 0) && (other.get_R_comp() != 0)){
double first = ((this->c_R)*other.get_R_comp() + (this->c_I)*other.get_I_comp())/(other.get_R_comp()*other.get_R_comp() + other.get_R_comp()*other.get_R_comp());
double second = (this->c_I*other.get_R_comp() + c_R*other.get_I_comp())/(other.get_R_comp()*other.get_R_comp() + other.get_I_comp()*other.get_I_comp());
Complex ret(first,second);
return ret;
}
if((other.get_I_comp() == 0 ) && (other.get_R_comp() != 0)){
Complex ret(this->c_R,this->c_I);
ret = ret *(1/other.get_R_comp());
return ret;
}
else{
Complex ret(this->c_R,this->c_I);
Complex neu(1/other.get_I_comp());
ret = ret * neu;
return ret;
}
}
void Complex::operator++(){
c_R++;
}
Complex& Complex::operator++(int dummy){
Complex temp = *this;
++temp;
c_R++;
return temp;
}
void Complex::operator+=(double other){
c_R += other;
}
void Complex::operator+=(Complex other){
c_R += other.get_R_comp();
c_I += other.get_I_comp();
}
void Complex::operator-=(double other){
c_R +=(-1*other);
}
void Complex::operator-=(Complex other){
c_R -= other.get_R_comp();
c_I -= other.get_I_comp();
}
void Complex::operator*=(double other){
Complex& reference = *this; //pass by reference editing
reference = reference* other;
}
void Complex::operator*=(const Complex& rhs){
Complex& reference = *this;
reference = reference * rhs;
}
void Complex::operator/=(double other){
Complex& reference = *this;
reference = reference / other;
}
void Complex::operator/=(const Complex& rhs){
Complex& reference = *this;
reference = reference / rhs;
}
double& Complex::operator[](int index){
if(index <= 1){
return(index == 0 ? c_R : c_I);
}
else{
throw std::out_of_range ("index outta bound");
}
}
void Complex::operator-(){
c_R*=(-1);
c_I*=(-1);
}
void Complex::operator+(){
if(c_R<0){
c_R*=(-1);
}
if(c_I<0){
c_I*=(-1);
}
}
Complex& Complex::add(double num){
Complex& reference = *this;
reference = reference + num;
return reference;
}
Complex& Complex::add(Complex other){
Complex& reference = *this;
reference = reference + other;
return reference;
}
Complex& Complex::subtract(double num){
Complex& reference = *this;
reference = reference - num;
return reference;
}
Complex& Complex::subtract(Complex other){
Complex& reference = *this;
reference = reference - other;
return reference;
}
Complex& Complex::multiply(double num){
Complex& reference = *this;
reference = reference*num;
return reference;
}
Complex& Complex::multiply(Complex other){
Complex& reference = *this;
reference = reference * other;
return reference;
}
Complex& Complex::divide(double num){
Complex& reference = *this;
reference = reference/num;
return reference;
}
Complex& Complex::divide(Complex other){
Complex& reference = *this;
reference = reference/other;
return reference;
}
Complex& Complex::abs(){
Complex& reference = *this;
+reference;
return reference;
}
ostream& operator<<(ostream& out, Complex& target){
out << "Real : ";
out << " " << target.getRealPart();
out << " imaginary :";
out <<target.getImaginaryPart();
return out;
}
istream& operator>>(const istream& input, Complex& target) {
string use;
input>>use;
stringstream convert(use);
int x = 0;
convert>>x;
target.set_R(x);
return input;
}
when doing calls such as
cout << "(" << number1 << ")" << " + " << "(" << number2 << ") = " << (number1 + number2) << endl;
it throws the following exception:
main.cpp:19:69: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘Complex’)
cout << "(" << number1 << ")" << " + " << "(" << number2 << ") = " << (number1 + number2) << endl;
In file included from main.cpp:1:0:
Complex.h:276:10: note: candidate: std::ostream& operator<<(std::ostream&, Complex&)
ostream& operator<<(ostream& out, Complex& target){
You have to overload the following function too!.
ostream& operator<<(ostream& out, Complex&& target){
out << "Real : ";
out << " " << target.getRealPart();
out << " imaginary :";
out <<target.getImaginaryPart();
return out;
}
Non-const references don't bind to temporaries.
So ostream& operator<<(ostream& out, Complex& target) can't be used in code that looks like cout << Complex{1.0} or cout << (complex1 + complex2), because in both cases the second argument is a temporary Complex instance.
A possible fix is to use const references when you don't plan to modify the argument:
ostream& operator<<(ostream& out, Complex const& target)
Another solution (for small objects) is to accept it by-value:
ostream& operator<<(ostream& out, Complex target)

Overloading issue

I'm trying to create a set of classes in order to handle complex numbers. I've seen that there is already a set of classes for the complex numbers, but because I'm learning C++ I thought it was a good idea to create a basic implementation. The problem comes up when I tried to overload the operator "/". I got a segfault and I can't understand if the problem is my implementation of the division:
complex.hpp :
#include <iostream>
#include <cstdlib>
class Complex {
float real;
float imm;
public:
Complex(float new_real = 0,float new_imm = 0) {this->real = new_real;this->imm = new_imm;}
void set(float new_real,float new_imm) {this->real = new_real; this->imm = new_imm;}
float get_real(void) const { return this->real;}
float get_imm(void) const { return this->imm;}
Complex conj(void) const {Complex tmp; tmp.set(this->real,-1.0 * this->imm); return tmp;}
friend std::ostream& operator<<(std::ostream& os, const Complex& cpx) {os << "Real: " << cpx.real << " Imm: " << cpx.imm << std::endl; return os; }
friend Complex operator*(const Complex& lhs,const Complex& rhs);
friend Complex operator+(const Complex& lhs,const Complex& rhs);
friend Complex operator+(const Complex& lhs,const float& rhs);
};
complex.cpp:
#include "complex.hpp"
Complex operator*(const Complex& lhs,const Complex& rhs)
{
float real_part = (lhs.real * rhs.real) - ( lhs.imm * rhs.imm);
float imm_part = (lhs.real * rhs.imm) + ( lhs.imm * rhs.real);
Complex result;
result.set(real_part,imm_part);
return result;
}
Complex operator+(const Complex& lhs,const Complex& rhs)
{
float real_part = lhs.real + rhs.real;
float imm_part = lhs.imm + rhs.imm;
Complex result;
result.set(real_part,imm_part);
return result;
}
Complex operator+(const Complex& lhs,const float& rhs)
{
float real_part = lhs.real + rhs;
float imm_part = lhs.imm;
Complex result;
result.set(real_part,imm_part);
return result;
}
Complex operator/(const Complex& lhs,const Complex& rhs)
{
Complex numerator(0,0);
numerator = rhs * rhs.conj();
Complex denominator(0,0);
denominator = lhs * rhs.conj();
Complex result;
float real_numerator = numerator.get_real();
result = denominator / real_numerator;
return result;
}
Complex operator/(const Complex& lhs,const float& rhs)
{
float real_part = lhs.get_real() / rhs;
float imm_part = lhs.get_imm() / rhs;
Complex result;
result.set(real_part,imm_part);
return result;
}
The whole idea of the division between 2 complex is to multiply the numerator and denominator for the conjugate of the numerator in order to have only a real number on the numerator. Just to make it clear :
(a + ib) / (c + id) = ((a + ib) / (c + id)) * ((c - id) / (c - id)) = ((a + ib) * (c - id)) / (c^2 + d^2)
Now when I try to do this:
main.cpp :
int main(int argc, char *argv[])
{
Complex x(4,8);
Complex y(3,7);
Complex result = x / y;
result = x / 6;
return 0;
}
I got this segfault, which I don't understand:
(gdb) break main
Breakpoint 2 at 0x401c56: file equalization_main.cpp, line 49.
(gdb) r
The program being debugged has been started already.
Start it from the beginning? (y or n) y
`/home/campiets/workspace/frontend/dfe_equalizer_fe/dev/view/src_c/test' has changed; re-reading symbols.
Starting program: /home/campiets/workspace/frontend/dfe_equalizer_fe/dev/view/src_c/test
Breakpoint 2, main (argc=1, argv=0x7fffffffbf08) at equalization_main.cpp:49
49 Complex x(4,8);
(gdb) n
50 Complex y(3,7);
(gdb) n
51 Complex result = x / y;
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401e64 in Complex::Complex (this=<error reading variable: Cannot access memory at address 0x7fffff3feff8>, new_real=<error reading variable: Cannot access memory at address 0x7fffff3feff4>,
new_imm=<error reading variable: Cannot access memory at address 0x7fffff3feff0>) at complex.hpp:38
38 Complex(float new_real = 0,float new_imm = 0) {this->real = new_real; this->imm = new_imm;}
Any ideas ?
Complex operator/(const Complex& lhs,const Complex& rhs)
{
...
Complex denominator...;
...
float real_numerator = ...;
result = denominator / real_numerator;
...
}
That's infinite recursion.
Since the compiler hasn't seen operator/(const Complex &lhs, const float &rhs), it converts the float argument to Complex and hence you get recursion.
The simplest solution is to declare or define operator/(const Complex &lhs, const float &rhs) before operator/(const Complex &lhs, const Complex &rhs).
My preference would be to implement the operators as class members, though. That yields simpler source code and solves the problem too.
The function
Complex operator/(const Complex& lhs,const Complex& rhs) { ... }
causes stack overflow since the line
result = denominator / real_numerator;
ends up being interpreted as:
result = denominator / Complex(real_numerator);
You can resolve that problem by defining or declaring
Complex operator/(const Complex& lhs, const float& rhs)
before it.
If you change your code to use:
Complex operator/(const Complex& lhs,const float& rhs)
{
return Complex(lhs.get_real()/rhs, lhs.get_imm()/rhs);
}
Complex operator/(const Complex& lhs,const Complex& rhs)
{
...
}
your program will work ok.
A suggestion for simplifying the above operator/ function.
If you add the following member function
float magnitude_square() const { return (real*real + imm*imm); }
then you can use
Complex operator/(const Complex& lhs,const Complex& rhs)
{
return (lhs * rhs.conj())/rhs.magnitude_square());
}

operator * overload c++

I am trying to make a program that can opearate with complex numbers. However i got stuck with operator * I cannot figure out how to make these 2 cases work:
First:
c = 10 * d;
cout << c << endl;
Second:
c = d * 10;
cout << c << endl;
This is my header:
class Complex
{
private:
double Real, Imag;
public:
Complex() : Real(), Imag()
{
}
//----------------------------------------------------------------------
Complex (double Real) //Initialization with only one variable
{
this->Real = Real;
Imag = 0;
}
//----------------------------------------------------------------------
Complex (double Real, double Imag) //Complete initialization
{
this->Real = Real;
this->Imag = Imag;
}
//----------------------------------------------------------------------
Complex & operator = (const Complex &s)
{
Real = s.Real;
Imag = s.Imag;
return *this;
}
//----------------------------------------------------------------------
Complex operator * (Complex s) // (r + i) * x
{
this->Real *= s.Real;
this->Imag *= s.Real;
return *this;
}
//----------------------------------------------------------------------
Complex & operator *= (Complex s) //Reference
{
Real *= s.Real;
Imag *= s.Imag;
return *this;
}
//----------------------------------------------------------------------
friend Complex operator * (Complex s1, Complex s2);
//----------------------------------------------------------------------
friend ostream &operator << (ostream &s, const Complex &c)
{
s << c.Real << " + " << c.Imag;
return s;
}
};
//Out of class functions
inline Complex operator * (Complex s1, Complex s2) // x * (r + i)
{
s2.Real *= s1.Real;
s2.Imag *= s1.Real;
return s2;
}
//----------------------------------------------------------------------
bool Complex::operator == (const Complex &s) const
{
return (this->Real == s.Real && this->Imag == s.Imag);
}
//----------------------------------------------------------------------
#endif /* __Complex_H__ */
My idea was to use operator inside class for second case, and outside for first case. But I got error:
error: ambiguous overload for 'operator*' in 'd * 10
How to make it clear to compiler which overload to use?
My main is:
#include <iostream>
#include "complex.h"
using namespace std;
int main()
{
Complex c, d(3, 5);
c = 10 * d;
cout << c << endl;
c = d * 10;
cout << c << endl;
}
In the first case, the friend non-class method is invoked without ambiguity because first parameter is not a Complex but can be built as such using the double to Complex constructor
In the second case, member method * and friend function can be applied, hence the error.
There's no need for a friend operator using 2 Complex objects. It's only useful when first parameter is a non-class object / a class object where you cannot set/change the behaviour of *
You'd be better off with:
friend Complex operator * (double s1, const Complex &s2);
Notes:
standard library has a very good std::complex implementation.
it would be better to use constant references rather than value parameter passing
overloading member operator*(double s1) would be interesting to avoid converting to a Complex when you want to multiply by a real value.

istream extraction values with formatted string

I have this formatted string in an istream.
(5, -4)
Let say :
open parenthesis
an integer number
comma and space
another integer number
close parenthesis
I would like to know what is the best approach to extract both integers and validate the string formatting.
This is in a class like this :
class MyPoint
{
public:
MyPoint() = default;
~MyPoint() = default;
...
friend ostream & operator>>(ostream & lhs, MyPoint const & rhs);
...
private:
int x, y;
};
ostream & operator>>(ostream & lhs, MyPoint const & rhs) {
// ???
}
Many thanks to all.
Here is my header file
#ifndef MYPOINT_H
#define MYPOINT_H
#include <iostream>
using namespace std;
class MyPoint
{
public:
MyPoint() : mX{ 0 }, mY{ 0 } { ; }
MyPoint(int x, int y) : mX{ x }, mY{ y } { ; }
~MyPoint() = default;
int x() const { return mX; }
int y() const { return mY; }
void setX(int x) { mX = x; }
void setY(int y) { mY = y; }
MyPoint operator-() const { return MyPoint(-mX, mY); }
MyPoint operator+(MyPoint rhs) const { rhs.mX += mX; rhs.mY += mY; return rhs; }
MyPoint operator-(MyPoint rhs) const { rhs.mX = mX - rhs.mX; rhs.mY = mY - rhs.mY; return rhs; }
MyPoint operator*(MyPoint rhs) const { rhs.mX *= mX; rhs.mY *= mY; return rhs; }
MyPoint operator/(MyPoint rhs) const { rhs.mX = mX / rhs.mX; rhs.mY = mY / rhs.mY; return rhs; }
MyPoint operator%(MyPoint rhs) const { rhs.mX = mX % rhs.mX; rhs.mY = mY % rhs.mY; return rhs; }
friend MyPoint operator+(int lhs, MyPoint const & rhs);
friend MyPoint operator-(int lhs, MyPoint const & rhs);
friend MyPoint operator*(int lhs, MyPoint const & rhs);
friend MyPoint operator/(int lhs, MyPoint const & rhs);
friend MyPoint operator%(int lhs, MyPoint const & rhs);
friend ostream & operator<<(ostream & lhs, MyPoint const & rhs);
friend istream & operator>>(istream & lhs, MyPoint & rhs);
private:
int mX, mY;
};
#endif //MYPOINT_H
And here my source file
#include "MyPoint.h"
MyPoint operator+(int lhs, MyPoint const & rhs) {
return MyPoint(lhs + rhs.mX, lhs + rhs.mY);
}
MyPoint operator-(int lhs, MyPoint const & rhs) {
return MyPoint(lhs - rhs.mX, lhs - rhs.mY);
}
MyPoint operator*(int lhs, MyPoint const & rhs) {
return MyPoint(lhs * rhs.mX, lhs * rhs.mY);
}
MyPoint operator/(int lhs, MyPoint const & rhs) {
return MyPoint(lhs / rhs.mX, lhs / rhs.mY);
}
MyPoint operator%(int lhs, MyPoint const & rhs) {
return MyPoint(lhs % rhs.mX, lhs % rhs.mY);
}
ostream & operator<<(ostream & lhs, MyPoint const & rhs) {
return lhs << "(" << rhs.mX << "," << rhs.mY << ")";
}
istream & operator >> (istream & lhs, MyPoint & rhs) {
return lhs >> "(" >> rhs.mX >> "," >> rhs.mY >> ")"; // HERE is the compiling error
}
And finally, the tests in the main
MyPoint p1, p2(2, -2);
cout << p1 << endl;
cout << p2 << endl;
With this file, I got this error :
Error C2679 binary '>>': no operator found which takes a right-hand operand of type 'const char [2]' (or there is no acceptable conversion)
For situations like this, I've often found it handy to define an overload of operator>> to read a predefined string from a stream:
std::istream &operator>>(std::istream &is, char const *pat) {
char ch;
while (isspace(static_cast<unsigned char>(is.peek())))
is.get(ch);
while (*pat && is && *pat == is.peek() && is.get(ch)) {
++pat;
}
// if we didn't reach the end of the pattern, matching failed (mismatch, premature EOF, etc.)
if (*pat) {
is.setstate(std::ios::failbit);
}
return is;
}
With this, reading your format might look something like this:
istream & operator>>(istream & lhs, MyPoint & rhs) {
return lhs >> "(" >> rhs.x >> "," >> rhs.y >> ")";
}
This will do like most typical overloads and set the stream's fail bit if the pattern you've given isn't matched. As it stands now, each string in the input can be preceded by arbitrary white space (just like conversions for numbers and such).
There is technically a minor bug here: as it stands right now, this uses the global locale's definition of whitespace. To be really correct, it should probably use the definition provided in the locale associated with the input stream.
Also note that I had to change your definition of operator>> bit; in the question it looks like an overload of operator<<, with just those two characters changed to get operator>> instead.
For a quick example:
#include <iostream>
std::istream &operator>>(std::istream &is, char const *pat) {
// implementation above
}
class Point {
int x, y;
friend std::istream &operator>>(std::istream &is, Point &p) {
return is >> "(" >> p.x >>"," >> p.y >> ")";
}
friend std::ostream &operator<<(std::ostream &os, Point const &p) {
return os << "(" << p.x <<", " << p.y << ")";
}
};
int main() {
Point p;
std::cout << "Please enter a point: ";
std::cin >> p;
std::cout << "Thanks. Point: " << p << '\n';
}
Tested with VC++ 2013, VC++ 2015, and g++ 6.1 (but this isn't pushing the limits of compilers at all, so I'd expect it to work fine even with compilers so old they're horribly broken in general (e.g., gcc 2.x or VC++ 6.0).

Operator>> Overloading

I am implementing a complex number using operator overloading. In the program, the user enters a complex number ALWAYS in the form:
a + bi
So, in example...
25.0 + 3.6i
Assume that the user will always enter both the real and the imaginary parts of the complex number, e.g., the user will enter "5 + 0i" (and not "5") or "0 - 6.2i" (and not "-6.2i").
My problem is that in main() I have the following code:
ComplexNumber c1;
cin >> c1;
cout << c1;
and the code prints:
0 + 0i
...when I entered "4.2 + 8.3i" into the prompt during runtime.
Here is my implementation of my operator>> class:
istream & operator>>(istream & in, ComplexNumber & n) {
string real;
string imag;
bool done = false;
int sign = 1;
string num;
in >> num;
int length;
for (int i = 0; i < num.length(); i++) {
if (num.at(i) == 'i') {
imag = num.substr((i - length), i);
}
else if (num.at(i) == '-') {
sign = -1;
}
else if (num.at(i) == ' ') {
if (!done) {
real = num.substr(i);
done = true;
}
length = 0;
}
length++;
}
n = ComplexNumber(atof(real.c_str()), atof(imag.c_str()) * sign);
return in;
}
Here is my implementation of operator<< class:
ostream & operator<<(ostream & out, const ComplexNumber & n) {
n.print(out);
return out;
}
Here is my implementation of the ComplexNumber member class print():
void ComplexNumber::print(ostream & out) const {
if (imag >= 0)
out << real << " + " << imag << "i";
else
out << real << " - " << (-1 * imag) << "i";
}
This is my ComplexNumber header file for further details:
#ifndef COMPLEXNUMBER_H
#define COMPLEXNUMBER_H
#include <iostream>
using namespace std;
class ComplexNumber {
public:
// constructors
ComplexNumber();
ComplexNumber(double real_part, double imaginary_part);
ComplexNumber(const ComplexNumber & rhs);
// named member functions
void print(ostream & out = cout) const;
bool equals(const ComplexNumber & rhs) const;
// assignment operators
const ComplexNumber & operator=(const ComplexNumber & rhs);
const ComplexNumber & operator+=(const ComplexNumber & rhs);
const ComplexNumber & operator-=(const ComplexNumber & rhs);
const ComplexNumber & operator*=(const ComplexNumber & rhs);
private:
double real;
double imag;
};
// arithmetic operators
ComplexNumber operator+(const ComplexNumber & lhs, const ComplexNumber & rhs);
ComplexNumber operator-(const ComplexNumber & lhs, const ComplexNumber & rhs);
ComplexNumber operator*(const ComplexNumber & lhs, const ComplexNumber & rhs);
// relational operators
bool operator==(const ComplexNumber & lhs, const ComplexNumber & rhs);
bool operator!=(const ComplexNumber & lhs, const ComplexNumber & rhs);
// I/O operators
ostream & operator<<(ostream & out, const ComplexNumber & n);
istream & operator>>(istream & in, ComplexNumber & n);
#endif
Any help with my implementations would be great.
Essentially your operator >> is way too complex, and doesn’t even handle errors properly. You shouldn’t read the value into a string to begin with – read it directly into a number. Furthermore, after each read operation you need to check (and potentially set) the stream’s state.
istream& operator >>(istream& in, ComplexNumber& value) {
int re;
if (not (in >> re)) {
return in;
char pm;
if (not (in >> pm) or (pm != '+' and pm != '-') {
in.setstate(ios::failbit);
return in;
}
int im;
if (not (in >> im))
return in;
char i;
if (not (in >> i) or i != 'i') {
in.setstate(ios::failbit);
return in;
}
value = ComplexNumber {re, (pm == '-' ? -im : im)};
return in;
}
(I used C++11 initialisers because I’m lazy ….)
And, yes, this can be written even shorter by pulling the whole reading into a single chainged expression:
istream& operator >>(istream& in, ComplexNumber& value) {
int re;
int im;
char pm;
char i;
if (not (in >> re >> pm) or
(pm != '+' and pm != '-') or
not (in >> im >> i) or
i != 'i')
{
in.setstate(ios::failbit);
return in;
}
value = ComplexNumber {re, (pm == '-' ? -im : im)};
return in;
}
Whether this is better depends on the audience. Personally, I do find it more (!) readable than the first version. A more structured alternative (which would be overkill for such a simple case) is Boost.Qi which allows very elegant parser construction.
This part:
string num;
in >> num;
It reads only one word from input. You would need to call it several times to read something like 4.2 + 8.3i, which has three words.