overloading operator * c++ - c++

I have been trying to compile this program but it is giving me an error in regards to overloading the * operator for one of the functions: complex operator *(double n)const
When I try to compile I get the error: no match for 'operator*' in '2 * c'
Here is the header file:
Complex.h
#ifndef COMPLEX0_H
#define COMPLEX0_H
class complex {
double realNum;
double imagNum;
public:
complex();
complex(double x,double y);
complex operator *(double n)const;
complex operator *(const complex &c1)const;
friend std::istream &operator>>(std::istream &is,complex &cm);
friend std::ostream &operator<<(std::ostream &os,const complex &cm);
};
#endif
Here is the cpp:
Complex.cpp
#include "iostream"
#include "complex0.h"
complex::complex() {
imagNum = 0.0;
realNum = 0.0;
}
complex::complex(double x, double y) {
realNum = x;
imagNum = y;
}
complex complex::operator *(const complex& c1) const{
complex sum;
sum.realNum=realNum*c1.realNum-c1.imagNum*imagNum;
sum.imagNum=realNum*c1.imagNum+imagNum*c1.realNum;
return sum;
}
complex complex::operator *(double n)const{
complex sum;
sum.realNum=realNum*n;
sum.imagNum=imagNum*n;
return sum;
}
std::istream &operator >>(std::istream& is, complex& cm) {
is >> cm.realNum>> cm.imagNum;
return is;
}
std::ostream &operator <<(std::ostream& os, const complex& cm){
os<<"("<<cm.realNum<<","<<cm.imagNum<<"i)"<<"\n";
return os;
}
main.cpp
#include <iostream>
using namespace std;
#include "complex0.h"
int main() {
complex a(3.0, 4.0);
complex c;
cout << "Enter a complex number (q to quit):\n";
while (cin >> c) {
cout << "c is " << c << "\n";
cout << "a is " << a << "\n";
cout << "a * c" << a * c << "\n";
cout << "2 * c" << 2 * c << "\n";
cout << "Enter a complex number (q to quit):\n";
}
cout << "Done!\n";
return 0;
}
Can someone explain to me what I have done wrong?

The member function operator only applies when the first operand is of your class type. If you want to handle the case where the second operand is of your type, you need also a free function (in which we simply delegate to the member function by virtue of commutativity of the operation):
complex operator*(double n, complex const & x)
{
return x * n;
}
(Please note that the standard library already contains <complex>.)

You have a member function defined as follows:
complex complex::operator *(double n) const;
That will let you do things like: complex_number * 3.0, but not 3.0 * complex_number. However, you can't create a member function that will let you do 3.0 * complex_number. The only place you could create that member function, is inside the definition of double, which you can't change.
Instead of doing it as member functions though, you can also do it as free-standing functions:
complex operator*(complex x, double n); // Called for complex_number * 2.0
complex operator*(double n, complex x); // Called for 2.0 * complex_number

Related

Input/Output Operators Overloading in C++

Stuck with ostream/istream operator overloading
Q1. why we are using ostream& operator as friend?
Q2. Why we are passing two arguments in ostream & operator << (ostream &out, const Complex &c)
Q3. why we are referencing to Cout and in ? istream & operator >> (istream &in, Complex &c).
Ref to: Overloading stream Oerator overloading- Geeks4Geeks
HERE IS THE CODE
#include <iostream>
using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);
};
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
istream & operator >> (istream &in, Complex &c)
{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imaginary Part ";
in >> c.imag;
return in;
}
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
A1. To access the private members
A2. The first argument is the stream and the second is the object. operator<< and operator>> expect two arguments
A3. Because they are modified in the function. The functions read from resp. write into the stream.
In addition:
Don't use using namespace std;
Don't initialize members in the constructor body. Use the constructor initializer list
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
should be
Complex(int r = 0, int i = 0) : real(r), imag(i) {}

Logical error with overloaded operator C++

I've been making a class called Complex for storing and working with complex numbers. I'm having issues where my overloaded + and * functions return an obscenely large number, which I can only presume has something to do with pointers, but I'm very new to using them. I've copied the output here:
c1: 1 - i5
c2: -4 + i3
c1 + c2: -9.25596e+061 - i9.255
c1 * c2: -9.25596e+061 - i9.255
Press any key to continue . . .
Here is the class architecture:
// Complex.h
#include <iostream>
#include <cmath>
using namespace std;
class Complex
{
friend std::ostream &operator<<(std::ostream &, const Complex &);
friend std::istream &operator>>(std::istream &, Complex &);
friend Complex &operator+(const Complex &, const Complex &);
friend Complex &operator+(const Complex &, const double &);
friend Complex &operator+(const double &, const Complex &);
friend Complex &operator*(const Complex &, const Complex &);
friend Complex &operator*(const Complex &, const double &);
friend Complex &operator*(const double &, const Complex &);
public:
explicit Complex(double re=0, double im=0);
void setReal(double re);
void setImag(double im);
double &getReal();
double &getImag();
~Complex();
private:
double real;
double imag;
};
And here I have the relevant portions of my program:
// Complex.cpp
#include "Complex.h"
ostream &operator<<(ostream &output, const Complex &num)
{
output << num.real << (num.imag >= 0 ? " + i" : " - i") << abs(num.imag);
return output;
}
Complex &operator+(const Complex &num1, const Complex &num2)
{
Complex sum(num1.real + num2.real, num1.imag + num2.imag); // Create new complex by summing elements
return sum;
}
Complex &operator*(const Complex &num1, const Complex &num2)
{
Complex prod(num1.real * num2.real - num1.imag * num2.imag, num1.real * num2.imag + num1.imag * num2.real); // Create new complex by expansion
return prod;
}
Complex::Complex(double re, double im)
{
real = re;
imag = im;
}
int main() {
Complex c1(1.0, -5.0);
Complex c2(-4.0, 3.0);
cout << "c1: " << c1 << endl;
cout << "c2: " << c2 << endl;
cout << "c1 + c2: " << c1 + c2 << endl;
cout << "c1 * c2: " << c1 * c2 << endl;
system("pause");
}
I feel bad bothering you guys about this. Do you possibly know of a site that does a good job of explaining concepts for C++ like pointers, least-privilege, polymorphism, inheritance, etc?
Sorry for asking basic questions on here, but it's hard to find resources that explain this stuff clearly.
Wrong return type:
Complex &operator+(const Complex &num1, const Complex &num2)
^^^^^^^^^
You're creating a temporary Complex and returning it by reference, and then it gets destroyed so you have a dangling reference. Since operator+ is constructing a new object and returning it, it should return it by value... so the signature should be:
Complex operator+(Complex const&, Complex const& );
The problem is that most of your overloaded operators return a reference to a local var, which is destroyed when the operator function returns, leaving you with a dangling reference. Try changing your operators to return a Complex rather than a Complex &:
Complex operator+(const Complex &num1, const Complex &num2)
{
Complex sum(num1.real + num2.real, num1.imag + num2.imag); // Create new complex by summing elements
return sum;
}

type transform by using constructor in c++ didn't work?

My code can't run well, can anybody tell me what happened to my otest.cpp?
: ~$ g++ --version
g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//filename: otest.cpp
#include <iostream>
using namespace std;
class Complex; // declaration
class Victor
{
private:
int x, y;
public:
Victor(int xx = 0, int yy = 0) { x = xx; y = yy; }
friend ostream & operator <<(ostream & ostr, Victor & v);
// operator Complex() { return Complex(x,y); }
int getX() { return x;}
int getY() { return y;}
Victor(Complex & c) { x = c.getReal(); y = c.getImg(); }
};
class Complex
{
private:
int real, img;
public:
Complex(int re= 0, int im = 0) { real = re; img = im; }
friend ostream & operator<<(ostream & ostr,Complex & c);
// operator Victor() { return Victor(real,img); }
int getReal() { return real;}
int getImg() { return img; }
Complex(Victor & v) { real = v.getX(); img = v.getY(); }
};
std::ostream& operator<< (std::ostream& ostr, Complex& c)
{ ostr << c.real << " + " <<c.img << " i";
return ostr;
}
std::ostream& operator<< (std::ostream& ostr, Victor v)
{
ostr << "( " << v.x << ", " << v.y << " )" ;
return ostr;
}
int main()
{
Victor v1(3,5);
Victor v2;
Complex c1(5,6);
Complex c2;
v2 = Victor(c1);
cout << v2 << endl;
cout << c1<<endl;
c2 = Complex(v1);
cout << c2 <<endl;
cout << v1 <<endl;
return 0;
}
Work through the errors in order, and fix each problem in turn.
First error:
test.cpp: In constructor ‘Victor::Victor(Complex&)’:
test.cpp:17:40: error: invalid use of incomplete type ‘class Complex’
Victor(Complex & c) { x = c.getReal(); y = c.getImg(); }
You can't use the Complex type here since it hasn't been defined yet. Just declare the function at this point:
Victor(const Complex &);
and define it after the definition of Complex
Victor::Victor(const Complex & c) { x = c.getReal(); y = c.getImg(); }
(I took the liberty of adding const since that's appropriate here. You might also want to rename the class Vector, since it appears to represent a vector not a victor.)
Second error:
test.cpp:10:17: error: ‘int Victor::x’ is private
test.cpp:43:23: error: within this context
ostr << "( " << v.x << ", " << v.y << " )" ;
This is because you declare a function with one signature (taking its second argument by reference)
friend ostream & operator <<(ostream & ostr, Victor & v);
and define a different overload taking its argument by value:
std::ostream& operator<< (std::ostream& ostr, Victor v)
Make the both match; const Victor& is the most appropriate type. Alternatively, you could define the function within the class definition:
class Victor
{
// ...
friend ostream & operator <<(ostream & ostr, const Victor & v) {
return ostr << "( " << v.x << ", " << v.y << " )" ;
}
// ...
};
Or you could implement the function using the public interface, with no need for a friend declaration:
std::ostream& operator<< (std::ostream& ostr, const Victor & v) {
return ostr << "( " << v.getX() << ", " << v.getY() << " )" ;
}
After fixing those errors, the code compiles and produces sensible-looking output.
The code shall not be compiled because in this point where constructor
Victor(Complex & c) { x = c.getReal(); y = c.getImg(); }
is defined the compiler knows nothing whether class Complex has methods getReal and getImg
You have only do declare the constructor in class Victor and define it only after the definition of class Complex.
Take into account that it would be better that some member functions and objects would have qualifier const. For example functions getReal and getImg could be declared with qualifier const. Also the parameter in the constructor above could be declared with qualifier const.
Victor( cosnt Complex &c );
Or for example operator << could be declared like
friend std::ostream & operator <<( std::ostream &ostr, const Complex &c );
friend std::ostream & operator <<( std::ostream &ostr, const Victor &v );

Private members of class - within this context

I get weird notification that I'm using private members of class - which is entirely valid, but I though that I'm allowed to do so, since I did say that the method I'm using is a friendly one.
Take a look at this:
#include <iostream>
using namespace std;
class complex {
private:
double Re, Im;
public:
complex(): Re(0.0), Im(0.0){}
complex(double Re, double Im): Re(Re), Im(Im){}
double getRe() const { return Re; }
double getIm() const { return Im; }
friend complex operator+(const complex&, const complex&);
friend ostream& operator<<(ostream&, const complex&);
friend istream& operator>>(istream &, const complex &); // FRIENDLY FUNCTION
};
complex operator+(const complex& a, const complex& b) {
double r, i;
r = a.getRe()+ b.getRe();
i = a.getIm() + b.getIm();
return complex(r, i);
}
ostream& operator<<(ostream& out, const complex &a) {
out << "(" << a.getRe() << ", " << a.getIm() << ")" << endl;
return out;
}
istream &operator>>(istream &in, complex &c)
{
cout<<"enter real part:\n";
in>>c.Re; // ** WITHIN THIS CONTEXT ERROR **
cout<<"enter imag part: \n";
in>>c.Im; // ** WITHIN THIS CONTEXT ERROR **
return in;
}
int main(void) {
complex a, b,c;
cin >> a;
cin >> b;
c = a+b;
cout << c;
}
Should I declare some sort of setFunction within the class in order to get the values which are private ?
istream& operator>>(istream &, const complex &);
is not the same as
istream &operator>>(istream &in, complex &c);
Spot the difference left as exercise to the reader.

OOP C++ first compiler error

Please help this newbie, here's my code:
#include <iostream>
using namespace std;
class Complex {
private:
float r, i;
public:
Complex(float rr, float ii) : r(rr), i (ii) {}
float GiveRe () { return r; }
float GiveIm () { return i; }
void Setit (float rr, float ii) {
r = rr;
i = ii;
}
};
Complex a(10, 20);
Complex sumit (Complex &ref) {
static Complex sum (0, 0);
sum.Setit(sum.GiveRe() + ref.GiveRe(), sum.GiveIm() + ref.GiveIm());
return sum;
}
int main () {
Complex sumvalue = sumit (a);
cout << sumvalue << endl;
return 0;
}
error: no match for 'operator<<' in 'std::cout << sumvalue'.
The program should output the sum of a complex number.
cout can't tell what you want to output, you need to specify the operator<< in the class or make it possible to implicitly convert your class to a compatible type.
http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/
Rudolf Mühlbauer's code as implemented in your class:
Add this somewhere within the class header:
friend ostream& operator<<(ostream& out, const Complex& compl);
and this below the header:
ostream& operator<<(ostream& out, const Complex& compl)
{
return out << compl.r << "/" << compl.i;
}
Implementation should be changed to suit your exact needs.
Complex doesn't have an operator <<
ostream& Complex::operator << ( ostream& os )
{
// use os << field/method here to out put
return os;
}
Also if complex can be displayed to console in different ways, then you should think of using methods to display instead of cout <<
void Complex::DisplayToConsole()
{
std::cout << r << " " << i << '\n';
}
You have to overload the "<<" operator for Complex type.
#include <iostream>
using namespace std;
class Complex {
private:
float r, i;
public:
Complex(float rr, float ii) : r(rr), i (ii) {}
float GiveRe () { return r; }
float GiveIm () { return i; }
void Setit (float rr, float ii) {
r = rr;
i = ii;
}
};
ostream& operator<<(ostream& os, Complex& c)
{
float i;
os<<c.GiveRe();
if(c.GiveIm() < 0){
os<<"-j"<<c.GiveIm()*(-1);
}else{
os<<"+j"<<c.GiveIm();
}
return os;
}
Complex a(10, 20);
Complex sumit (Complex &ref) {
static Complex sum (0, 0);
sum.Setit(sum.GiveRe() + ref.GiveRe(), sum.GiveIm() + ref.GiveIm());
return sum;
}
int main () {
Complex sumvalue = sumit (a);
cout << sumvalue << endl;
return 0;
}
A complete minimal example:
#include <iostream>
using namespace std;
class C {
public:
int r, l;
// if the operator needs access to private fields:
friend ostream& operator<< (ostream&, const C&);
};
ostream& operator << (ostream& stream, const C& c) {
stream << c.r << "--" << c.l;
return stream;
}
int main() {
C c;
c.l = 1;
c.r = 2;
cout << c << endl;
}
C++ allows you to define operators. The STL uses the << operator for output, and the whole istream/ostream class hierarchy uses this operator to input/output.
Operators are implemented as functions, but always follow a very specific syntax. As in the example, ostream& operator << (ostream&, const MYTYPEHERE&) is the way to define ostream << operators.
When C++ encounters a statement, it has to deduce the types of all operands, and find (quite magically, indeed) a solution to the question: given my operands and operators, can i find a typing such that the statement gets valid?
These ofstream operators are defined for all basic types somewhere in <iostream>, so if you write cout << 10, the compiler finds an operator ostream& operator<< (ostream&, int).
If you want to be able to use userdefined types in this game, you have to define the operators. otherwise, a statement cout << sometype will not be valid. This is also the reason for the harsh compiler errors sometimes found in C++: "Well, i have some operators << defined, but none is compatible with your type!".
Because sometimes it is not favourable to implement operators for your types (if you only output them once, e.g.), i suggested to write:
cout << sum.re << "--" << sum.im << endl; // or similar
This way, you write less code, and you are flexible in the output format. Who knows if you want you complex number formatted differently next time? But this is another discussion.
Why complicating that much? Because C++ can be awfully complicated. It it very powerfull, but crammed with special syntax and exceptions to those. In the end, the difference to C lies exactly here: C++ does a much better job with type inference (needed for templates), often resulting in WTF?
On how to implement it in your code, i think the other answers provide nice solutions!
sumit(a) returns an object of type Complex, which cout was not defined to handle.