I'm having an issue trying to get some code for an assignment to compile. I've looked at similar issues (even ones that seem to be the same exact assignment), but none of the solutions worked.
my header file: 'complex.h':
#ifndef COMPLEX_H_INCLUDED
#define COMPLEX_H_INCLUDED
#include <iostream>
#include <cstdlib>
using namespace std;
class Complex
{
public:
// Consructors:
Complex();
Complex(double);
Complex(double, double);
// Operational Overloads:
const bool operator == (const Complex&);
const Complex operator + (const Complex&);
const Complex operator + (const double&);
const Complex operator - (const Complex&);
const Complex operator - (const double&);
const Complex operator * (const Complex&);
const Complex operator * (const double&);
friend ostream& operator << (ostream&, const Complex&);
friend istream& operator >> (istream&, Complex&);
private:
double real;
double imaginary;
};
#endif // COMPLEX_H_INCLUDED
My implementation code, 'complex.cpp':
#include "complex.h"
#include <iostream>
using namespace std;
/****************************************************************************
* Constructor () *
****************************************************************************/
inline Complex::Complex(){
real = 0;
imaginary = 0;
}
/****************************************************************************
* Constructor (double) *
****************************************************************************/
inline Complex::Complex(double realPart)
:real(realPart)
{
imaginary = 0;
}
/****************************************************************************
* Constructor (double, double) *
****************************************************************************/
inline Complex::Complex(double realPart, double imaginaryPart)
:real(realPart), imaginary(imaginaryPart)
{}
/****************************************************************************
* Operator '==' -- Compares two Complex objects *
* Returns: *
* -- True if their real and imaginary values are equal *
* -- False otherwise *
****************************************************************************/
inline const bool Complex::operator == (const Complex& rhs)
{
return ((this->real == rhs.real) && (this->imaginary == rhs.imaginary));
}
/****************************************************************************
* Operator '+' -- Adds two Complex objects *
* Returns: *
* -- The new Complex object *
****************************************************************************/
inline const Complex Complex::operator + (const Complex& rhs)
{
return (Complex((this->real + rhs.real), (this->imaginary + rhs.imaginary)));
}
/****************************************************************************
* Operator '+' -- Adds a real number to the Complex object *
* Returns: *
* -- The new Complex object *
****************************************************************************/
inline const Complex Complex::operator+(const double& rhs)
{
return Complex((this->real + rhs), this->imaginary);
}
/****************************************************************************
* Operator '-' -- Subtracts the number of another Complex object *
* Returns: *
* -- The new Complex object *
****************************************************************************/
inline const Complex Complex::operator - (const Complex& rhs)
{
return (Complex((this->real - rhs.real), (this->imaginary - rhs.imaginary)));
}
/****************************************************************************
* Operator '-' -- Subtracts a real number from the Complex object *
* Returns: *
* -- The new Complex object *
****************************************************************************/
inline const Complex Complex::operator-(const double& rhs)
{
return Complex((this->real - rhs), this->imaginary);
}
/****************************************************************************
* Operator '*' -- Multiplies together two Complex objects *
* Returns: *
* -- The new Complex object *
****************************************************************************/
inline const Complex Complex::operator * (const Complex& rhs)
{
return (Complex((this->real * rhs.real) - (this->imaginary * rhs.imaginary), (this->real * rhs.imaginary) + (this->imaginary * rhs.real)));
}
/****************************************************************************
* Operator '*' -- Mutltiplies the Complex object by a real number *
* Returns: *
* -- The new Complex object *
****************************************************************************/
inline const Complex Complex::operator * (const double& rhs)
{
return Complex((this->real * rhs), (this->imaginary * rhs));
}
/****************************************************************************
* Operator '<<' -- Outputs the Complex object in a comprehensive format *
* Returns: *
* -- A reference to the ostream *
****************************************************************************/
ostream& operator <<(ostream& out, const Complex& comp)
{
if(comp.real != 0)
{
out << comp.real;
if(comp.imaginary > 0)
out << " + ";
else if (comp.imaginary < 0)
out << " - ";
}
if(comp.imaginary != 0)
out << comp.imaginary << "i";
return out;
}
/****************************************************************************
* Operator '>>' -- Takes in a Complex object from the user *
* Returns: *
* -- A reference to the istream *
****************************************************************************/
istream& operator >>(istream& in, Complex& comp)
{
char sign; //Used to store input when looking for mathematical operators
bool neg = false; //Stores whether or not any input values are <0
// Checks for a negative value for the real
sign = std::cin.peek();
if(sign == '-'){
neg = true;
std::cin.ignore(1,'-');
}
in >> comp.real;
//Negates the real value if necessary
if(neg){
comp.real = -comp.real;
neg = false;
}
//Looks for the + or - operator, accounting for possible variations in whitespacing and hazardous input.
do{
in >> sign;
}while (sign == ' ');
if (sign == '-')
neg = true;
else if (sign != '+'){
cout << "You did not properly format the input of a complex number. \nPlease use the format: 'a+bi' where 'a' is the real number, and 'b' is the imaginary number." << endl;
cout << "The program is currently shutting down.";
exit(EXIT_FAILURE);
}
sign = std::cin.peek();
while(sign == ' ')
in >> sign;
in >> comp.imaginary;
if(neg)
comp.imaginary = -comp.imaginary;
}
And final class which implements complex.cpp:
#include <iostream>
#include "complex.cpp"
using namespace std;
int main()
{
Complex aComplex();
cout << "Please enter a complex number, in the form of 'a+bi', where 'a' is a real number and 'b' the imaginary number." << endl;
cin >> aComplex;
cout << "You entered the value: " << aComplex << endl;
return 0;
}
When I try to build the code, I get the error:
.../Complex/main.cpp|12|error: ambiguous overload for ‘operator>>’ in ‘std::cin >> aComplex'`
Anyone have any ideas? (I am using Code::Blocks 12.11 and using Ubuntu 13.04, if that helps.)
The problem is that aComplex is declared as a function! You probably meant to write one of the following:
Complex aComplex;
Complex bComplex = Complex();
Complex cComplex{};
Look for " most vexing parse" to get an explanation of why your aComplex is a function declaration.
Complex aComplex();
This doesn't call the constructor of Complex, it creates the people of a function taking zero arguments and returning an object of type Complex. The empty parenthesis should be removed if you want to instantiate an object:
Complex aComplex;
Related
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.
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;
}
I try to understand how this line of code in blow c++ program, and my questions are
return Rational(_n * rhs._d, _d * rhs._n);
how the _n refer to the first object data member?
how the temporary object refer get the a._n?
C++ program:
#include <iostream>
class Rational {
int _n;
int _d;
public:
Rational ( int numerator = 0, int denominator = 1 ) : _n(numerator), _d(denominator) {};
Rational ( const Rational & rhs ) : _n(rhs._n), _d(rhs._d) {}; // copy constructor
inline int numerator() const { return _n; };
inline int denominator() const { return _d; };
Rational operator / ( const Rational & ) const;
};
Rational Rational::operator / ( const Rational & rhs ) const {
return Rational(_n * rhs._d, _d * rhs._n);
}
// useful for std::cout
std::ostream & operator << (std::ostream & o, const Rational & r) {
return o << r.numerator() << '/' << r.denominator();
}
int main( int argc, char ** argv ) {
using namespace std;
Rational a = 7; // 7/1
Rational b(5, 3); // 5/3
cout <<"a is : " <<a << endl;
cout << " b is : "<< b << endl;
cout << " a/b is: "<< a / b << endl;
return 0;
}
which has out put of
a is : 7/1
b is : 5/3
a/b is: 21/5
this program is simple version of this program in github
To put it in a few words, the operator / can be written like this:
class Rational
{
//...rest of the stuff:
Rational Divide( const Rational & rhs) const
{
return Rational(_n * rhs._d, _d * rhs._n);
}
};
and instead of the operator / for result = a/b you can write result = a.Divide(b)
Basically operator / behaves the same way as Divide method:
Now , let's analyze the divide method:
you have:
result = a.Divide(b); // which is the same as result = a/b in your case
and
Rational Divide( const Rational & rhs) const
{
return Rational(_n * rhs._d, _d * rhs._n);
}
rhs is the argument passed to Divide which is the variable b.
_n and _d are the members of the variable a. You can also write them like this: this->_n and this->_d. Divide is a member function so it can access _n and _d directly.
Now to simplify this even further to understand the way it works, here is another way to write this:
class Radional {/*stuff*/};
Rational Divide( const Rational & a, const Rational & b)
{
return Rational(a._n * b._d, a._d * b._n);
}
For this example the result = a.Divide(b) transforms into result = Divide(a,b)
Notice that now you have a._n and a._d which is the first argument of function Divide
As a conclusion the expression a/b is just a very nice way of writing Divide(a,b) that c++ standard allows.
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.
I am trying to create a function that conjugate a complex number
for example A(2, 3) will turn into A(2,-3) by typing ~A
i have done a little code below but i guess it's wrong, i hope you can help me slove this.
i have quoted the part that i did wrong in the code below.
#include <iostream>
using namespace std;
class Complex
{
private:
double real;
double imaginenary;
public:
Complex();
Complex(double r, double i = 0);
// Declaration
Complex operator~(const Complex & c) const;
Complex operator+(const Complex & c) const;
Complex operator-(const Complex & c) const;
Complex operator*(const Complex & c) const;
Complex operator*(double n) const;
friend Complex operator*(double m, const Complex & c)
{ return c * m; }
friend ostream & operator<<(ostream & os, const Complex & c);
};
Complex::Complex()
{
real = imaginenary = 0;
}
Complex::Complex(double r, double i )
{
real = r;
imaginenary = i;
}
// Definition
Complex Complex::operator~(const Complex & c) const
{
Complex conj;
conj.imaginenary = -1 * imaginenary;
conj.real = real;
}
Complex Complex::operator+(const Complex & c) const
{
Complex sum;
sum.imaginenary = imaginenary + c.imaginenary;
sum.real = real + c.real;
return sum;
}
Complex Complex::operator-(const Complex & c) const
{
Complex diff;
diff.imaginenary = imaginenary - c.imaginenary;
diff.real = real - c.real;
return diff;
}
Complex Complex::operator*(const Complex & c) const
{
Complex mult;
mult.imaginenary = imaginenary * c.imaginenary;
mult.real = real * c.real;
return mult;
}
Complex Complex::operator*(double mult) const
{
Complex result;
result.real = real * mult;
result.imaginenary = imaginenary * mult;
return result;
}
ostream & operator<<(ostream & os, const Complex & c)
{
os << "(" << c.real <<"," << c.imaginenary<<"i)";
return os;
}
int main()
{
Complex A;
Complex B(5, 40);
Complex C(2, 55);
cout << "A, B, and C:\n";
cout << A <<"; " << B << ": " << C << endl;
cout << " complex conjugate is" << ~C << endl;
cout << "B + C: " << B+C << endl;
cout << "B * C: " << B*C << endl;
cout << "10 * B: " << 10*B << endl;
cout << "B - C: " << B - C << endl;
return 0;
}
The tilde (~) operator is a unary operator so it shouldn't accept a parameter (it works on *this). You also forgot to return a value from operator~.
Complex operator~() const
{
return Complex( real, -1 * imaginenary);
}
See your fixed code here
BTW: It's spelt imaginary.
try
Complex Complex::operator~() const
{
Complex conj;
conj.imaginenary = -1 * imaginenary;
conj.real = real;
return conj;
}
But it might be wiser to remove the operators from the class definition and create (friend) functions instead. It works better with implicit type conversion.
Lots of code, but if you would have compared your operator~ to e.g. operator+ , you would have spotted one detail - there's no return statement.
Complex Complex::operator~(const Complex & c) const
{
Complex conj;
conj.imaginenary = -1 * c.imaginenary;
conj.real = c.real;
return conj;
}
This should do.
Although it's not the best idea to return anything you've allocated inside nonglobal scope, since that region in the memory can be overwritten anytime. And btw it's imaginary, not imaginenary :)
friend Complex operator*(double m, const Complex & c) { return c * m; }
friend ostream & operator<<(ostream & os, const Complex & c);
Is there anyway to avoid using friend in this problem? because i have read that from the book but not quite understand it.