Additon of complex numbers using operator overloading in c++ - c++

Not able to understand a block of code in below given program.
Especially the variable, temp which has return type as the complex(the class name) and when we return the variable, temp where it gets returned to?
That is return(temp); in the program.
The Program
#include <iostream>
using namespace std;
class complex
{
public:
complex();//default constructors
complex(float real, float imag)//constructor for setting values
{
x = real;
y = imag;
}
complex operator +(complex);
void display(void);
~complex();
private:
float x;
float y;
};
complex::complex()
{
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
complex complex::operator+(complex c)
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return(temp);
}
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
void complex::display(void) {
cout << x << "+j" << y << "/n";
}
complex::~complex()
{
}
int main()
{
complex C1, C2, C3,C4;
C1 = complex(1, 3.5);//setting of first number
C2 = complex(2,2.7);//setting of second number
C4 = complex(2, 5);
C3 = C1 + C2+C4;//operator overloading
cout << "C1 = ";
C1.display();
cout << "\n C2 = ";
C2.display();
cout << "\n C4 = ";
C4.display();
cout << "\n C3 = ";
C3.display();
system("pause");
return 0;
}

complex C5;
C5=C1+C2;
means
C5=C1.operator+(C2)
equivalent to
complex temp;
temp.x = x + C2.x; /* x=C1.x*/
temp.y = y + C2.y; /* y=C1.y*/
C5=temp;

Related

Coordinate conversion in c++

I am trying to convert different coordinate systems. From polar to rectangular and vice versa. My pol_to_rect()function is not working properly. It is giving very small values(~10^(-44)) after converting and also before converting. There might be some problem while using the sin() and cos() functions. The rect_to_pol() is working fine for positive values.
Edit - When I changed atan() to atan2() how can I incorporate other values of x and y.
#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.1415926
class Polar; // Forward declaration
class Rectangular {
private:
float x, y;
public:
Rectangular() {} // default constructor
Rectangular(float mv_x, float mv_y) {
x = mv_x;
y = mv_y;
}
void showData() const;
Polar rect_to_pol();
float& get_x() {
return x;
}
float& get_y() {
return y;
}
};
void Rectangular::showData() const {
cout << "--Rectangular--" << endl;
cout << "x: " << x << "\t" <<"y: " << y << endl;
}
class Polar {
private:
float r;
float theta;
public:
Polar() {} // default constructor
Polar(float mv_r, float mv_theta) {
r = mv_r;
theta = mv_theta;
}
void showData();
Rectangular pol_to_rect();
float& get_r(){
return r;
}
float& get_theta() {
return theta;
}
};
void Polar::showData() {
cout << "--Polar--" << endl;
cout << "r:" << r << "\t" << "Theta(Radians):" << theta << endl;
}
Rectangular Polar::pol_to_rect() {
Rectangular temp;
temp.get_x() = r * cos(theta*(PI/180.0)); // in degrees
temp.get_y() = r * sin(theta*(PI/180.0));
return temp;
}
Polar Rectangular::rect_to_pol() {
Polar temp;
temp.get_r() = sqrt(pow(x, 2) + pow(y, 2));
temp.get_theta() = atan2(y, x);
return temp;
}
int main()
{
Rectangular r1(-1, -1), r2;
Polar p1(12.0, 30.0), p2;
r1.showData();
p2 = r1.rect_to_pol();
cout << "After Conversion (RECT TO POLAR)->" << endl;
p2.showData();
p1.showData();
r2 = p1.pol_to_rect();
cout << "After Conversion (POLAR TO RECT)" << endl;
r2.showData();
return 0;
}

operator overloading(using binaray friend function) class has no member, and member inaccessible

While doing a youtube tutorial on operator overloading, I'm having trouble fixing an operator overloading (using friend function) error message. The message received was about, class Complex has no member "operator+" and class
"Complex::real" declared at line 7 is inaccessible.
// link to the tutorial i'm struggling with
https://www.youtube.com/watch?v=AlCYu_mc-T8
// the error message starts around here://
#include "stdafx.h"
#include <iostream>
using namespace std;
class Complex
{
int real, imag;
public:
void read();
void show();
friend Complex operator+ (Complex , Complex); // Friend function declaration
};
void Complex::read()
{
cout << "Enter real value: ";
cin >> real;
cout << "Enter imaginary value: ";
cin >> imag;
}
void Complex::show()
{
cout << real;
if (imag < 0)
cout << "-i";
else
cout << "+i";
cout << abs(imag) << endl;
}
Complex Complex::operator+(Complex c1, Complex c2)
{
Complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return temp;
}
int main()
{
Complex c1, c2, c3;
c1.read();
c2.read();
c3 = c1 + c2; // invokes operator + (Complex, Complex)
cout << "Addition of c1 and c2 = ";
c3.show();
return 0;
}
The friend is not a member. Hence, change this line:
Complex Complex::operator+(Complex c1, Complex c2)
to :
Complex operator + (Complex c1, Complex c2)

Cannot retrieve data values from array quadraticExpression

So, in class for work we have to write a header class for quadratic expression. I have the header file done for the most part, however, when I proceed to run with the given .cpp file to test out the header file, it does not appear to read the values given in the array in the cpp file. When I debug, it just puts in garbage values for the values. To me I thought it made sense and can't see anything wrong with it. Unless am I missing something?
I constructed the following header file...
#pragma once
#include <cmath>
enum roots {
NO_ROOTS = 0,
ONE_ROOT = 1,
TWO_ROOTS = 2,
INFINITE_ROOTS = 3
};
class quadraticExpression
{
private:
double a, b, c;
public:
double evaluate(double x) const;
int getNumberOfRoots() const;
double getFirstRoot() const;
double getSecondRoot() const;
double getACoefficient() const;
double getBCoefficient() const;
double getCCoefficient() const;
quadraticExpression();
quadraticExpression(double a,
double b,
double c);
};
quadraticExpression::quadraticExpression()
{
a = 0;
b = 0;
c = 0;
}
inline quadraticExpression::quadraticExpression(double a, double b, double
c)
{
a = a;
b = b;
c = c;
}
;
double quadraticExpression::evaluate(double x) const
{
double y;
y = (a*(x * x)) + (b * x) + c;
return y;
}
int quadraticExpression::getNumberOfRoots() const
{
//return value from enum
double eins;
double zwei;
eins = getFirstRoot();
zwei = getSecondRoot();
if (eins == 0 && zwei == 0)
{
return TWO_ROOTS;
}
else if (eins == 0 || zwei == 0)
{
return ONE_ROOT;
}
else if (eins != 0 && zwei != 0)
{
return NO_ROOTS;
}
}
double quadraticExpression::getFirstRoot() const
{
//return one x value where y is 0
double root1 = (b * b);
double root2 = (4 * a*c);
double solutionOne;
double zUno;
zUno = (abs(b) + sqrt(root1 - root2)) / (2 * a);
solutionOne = (a*(zUno * zUno)) + (b * zUno) + c;
return solutionOne;
}
double quadraticExpression::getSecondRoot() const
{
//return another x value where y is 0
double root1 = (b * b);
double root2 = (4 * a*c);
double solutionTwo;
double zDos;
zDos = (abs(b) - sqrt(root1 - root2)) / (2 * a);
solutionTwo = (a*(zDos *zDos)) + (b *zDos) + c;
return solutionTwo;
}
double quadraticExpression::getACoefficient() const
{
return a;
}
double quadraticExpression::getBCoefficient() const
{
return b;
}
double quadraticExpression::getCCoefficient() const
{
return c;
}
And here is the .cpp tester file
#include <iostream>
#include "QuadraticExpression.h"
using namespace std;
void evaluateExpression(const quadraticExpression &);
int main()
{
quadraticExpression q[6] = { quadraticExpression(2.1, 3, -7),
quadraticExpression(1.4, 3.9, +7),
quadraticExpression(-.75, 0, 0),
quadraticExpression(0, .3, -7),
quadraticExpression(0, 0, 4),
quadraticExpression() };
for (int i = 0; i<6; i++)
evaluateExpression(q[i]);
return EXIT_SUCCESS;
}
void evaluateExpression(const quadraticExpression &q)
{
int errorsHandled = 0;
cout << q.getACoefficient() << " A " << endl;
cout << q.getBCoefficient() << " B " << endl;
cout << q.getCCoefficient() << " C " << endl;
cout << "f(-5) = " << q.evaluate(-5) << endl;
cout << "f(0) = " << q.evaluate(0) << endl;
cout << "f(5) = " << q.evaluate(5) << endl;
if (q.getNumberOfRoots() == INFINITE_ROOTS)
cout << "The Expression has Infinite Roots" << endl;
else if (q.getNumberOfRoots() == ONE_ROOT)
cout << "The Expression has One Root at x = " << q.getFirstRoot() <<
endl;
else if (q.getNumberOfRoots() == TWO_ROOTS)
{
cout << "The Expression has First Root at x = " << q.getFirstRoot() <<
endl;
cout << "The Expression has Second Root at x = " << q.getSecondRoot() <<
endl;
}
else
cout << "The Expression has No Roots" << endl;
try {
q.getFirstRoot();
}
catch (domain_error e) {
errorsHandled++;
}
try {
q.getSecondRoot();
}
catch (domain_error e) {
errorsHandled++;
}
cout << "Errors Handled: " << errorsHandled << endl;
cout << endl;
cout << endl;
}
I fathom I might not be properly acquiring the data values a, b, and c from the array given in the cpp file therefore it just collects garbage values, however I'm stumped here.
This won't work as you intend.
inline quadraticExpression::quadraticExpression(double a, double b, double c)
{
a = a;
b = b;
c = c;
}
You're just assigning the parameter variables to themselves, not assigning to the member variables of the class. Variables declared in a function take precedence over member variables with the same name.
You should give the parameters different names from the member variables, or assign like this->a = a;.
But if you're just initializing member variables from parameters, you don't need to do assignments at all, initializer lists are preferred (see C++: Where to initialize variables in constructor):
quadraticExpression::quadraticExpression(double a, double b, double c) : a(a), b(b), c(c)
{}
Similarly, the constructor with no arguments should use an initializer list:
quadraticExpression::quadraticExpression() : a(0), b(0), c(0)
{}

Newton method for computing an inverse

This is following the question I asked in this thread : Link error missing vtable
I defined a class 'function' and two others classes 'polynomial' and 'affine' that inherit from 'function'.
class function {
public:
function(){};
virtual function* clone()const=0;
virtual float operator()(float x)const=0; //gives the image of a number by the function
virtual function* derivative()const=0;
virtual float inverse(float y)const=0;
virtual ~function(){}
};
class polynomial : public function {
protected:
int degree;
private:
float *coefficient;
public:
polynomial(int d);
virtual~polynomial();
virtual function* clone()const;
int get_degree()const;
float operator[](int i)const; //reads coefficient number i
float& operator[](int i); //updates coefficient number i
virtual float operator()(float x)const;
virtual function* derivative()const;
virtual float inverse(float y)const;
};
class affine : public polynomial {
int a;
int b;
//ax+b
public:
affine(int d,float a_, float b_);
function* clone()const;
float operator()(float x)const;
function* derivative()const;
float inverse(float y)const;
~affine(){}
};
Method inverse in polyomial does not seem to work fine. It is based on the Newton method applied to the function x->f(x)-y for fixed y (the element for which we're computing the inverse) and the current polynomial f.
float polynomial::inverse(float y)const
{
int i=0;
float x0=1;
function* deriv=derivative();
float x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
while(i<=100 && abs(x1-x0)>1e-5)
{
x0=x1;
x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
i++;
}
if(abs(x1-x0)<=1e-5)
{
//delete deriv; //I get memory problems when I uncomment this line
return x1;
}
else
{
cout<<"Maximum iteration reached in polynomial method 'inverse'"<<endl;
//delete deriv; //same here
return -1;
}
}
double polynomial::operator()(double x)const
{
double value=0;
for(int i=0;i<=degree;i++) value+=coefficient[i]*pow(x,i);
return value;
}
polynomial* polynomial::derivative()const
{
if(degree==0)
{
return new affine(0,0,0);
}
polynomial* deriv=new polynomial(degree-1);
for(int i=0;i<degree;i++)
deriv[i]=(i+1)*coefficient[i+1];
return deriv;
}
I test this method with p:x->x^3 :
#include "function.h"
int main(int argc, const char * argv[])
{
polynomial p(3);
for(int i=0;i<=2;i++) p[i]=0;
p[3]=1;
cout<<"27^(1/3)="<<p.inverse(27);
return 0;
}
This script outputs 27^(1/3)=Maximum iteration reached in polynomial method 'inverse'
-1 even if I put 10,000 instead of 100. I've read some articles on the internet and it seems that it's a common way to compute the inverse.
the abs function prototype is: int abs(int)
So a test like abs(x1-x0)<=1e-5 won't behave as you expect; you compare a int with a float. In this case the float will be converted to int so it the same as abs(x1-x0)<=0
This is probably why you don't get the expected result - I suggest adding a few more printouts to get to the bottom of things.
Well, the problem was in method 'derivative'. Instead of using the 'operator[]' that I redefined, I used '->coefficient[]' and the main script worked fine for p.inverse(27) (only 14 iterations). I just replaced deriv[i]=(i+1)*coefficient[i+1]; with deriv->coefficient[i]=(i+1)*coefficient[i+1];
Check This Code :
#include<iostream>
#include<cmath>
#include<math.h>
using namespace std;
void c_equation(int choose, double x);
void Processes(double x, double fx1, double fdx1, int choose);
void main()
{
int choose,choose2;
double x;
system("color A");
cout << " " << endl;
cout << "=============================================================" << endl;
cout << "Choose Equation : " << endl;
cout << "_____________________________________" << endl;
cout << "1- x-2sin(x)" << endl;
cout << "2- x^2 + 10 cos(x)" << endl;
cout << "3- e^x - 3x^2" << endl;
cout << " " << endl;
cin >> choose;
cout << "If you have values press 1/ random press 2 :" << endl;
cin >> choose2;
if (choose2 == 1)
{
cout << " " << endl;
cout << "Enter Xo : " << endl;
cin >> x;
c_equation(choose, x);
}
else if (choose2 == 2)
{
x = rand() % 20;
cout << "Xo = " << x << endl;
c_equation(choose, x);
choose2 = NULL;
}
else
{
cout << "Worng Choice !! " << endl;
choose = NULL;
choose2 = NULL;
main();
}
}
void c_equation(int choose, double x)
{
double fx;
double fdx;
double fddx;
double result;
if (choose == 1)
{
fx = x - 2 * sin(x);
fdx = 1 - 2 * cos(x);
fddx = 2 * sin(x);
result = abs((fx * fddx) / pow(fdx, 2));
}
else if (choose == 2)
{
fx = pow(x, 2) + 10 * cos(x);
fdx = 2 * x - 10 * sin(x);
fddx = 2 - 10 * cos(x);
result = abs((fx * fddx) / pow(fdx, 2));
}
else if (choose == 3)
{
fx = exp(x) - 3 * pow(x, 2);
fdx = exp(x) - 6 * x;
fddx = exp(x) - 6;
result = abs((fx * fddx) / pow(fdx, 2));
}
else
{
cout << " " << endl;
}
//------------------------------------------------------------
if (result < 1)
{
cout << "True Equation :) " << endl;
Processes(x, fx, fdx , choose);
}
else
{
system("cls");
cout << "False Equation !!" << endl;
choose = NULL;
x = NULL;
main();
}
}
void Processes(double x, double fx, double fdx , int choose)
{
double xic;
for (int i = 0; i < 3; i++)
{
xic = x - (fx / fdx);
cout << " " << endl;
cout << "Xi = " << x << " " << "F(Xi) = " << fx << " " << " F'(Xi) = " << fdx << " " << " Xi+1 = " << xic << endl;
x = xic;
if (choose == 1)
{
fx = xic - 2 * sin(xic);
fdx = 1 - 2 * cos(xic);
}
else if (choose == 2)
{
fx = pow(xic, 2) + 10 * cos(xic);
fdx = 2 * xic - 10 * sin(xic);
}
else if (choose == 3)
{
fx = exp(xic) - 3 * pow(xic, 2);
fdx = exp(xic) - 6 * xic;
}
}
}

C++ another class member and overloading operator

I need to write program as follow:
#include <iostream>
using namespace std;
class Point
{
public:
double X;
double Y;
Point(){}
Point(double x, double y)
{
X = x;
Y = y;
}
};
class Circle
{
public:
Point P;
double R;
Circle(){}
Circle(Point p, double r)
{
P = p;
R = r;
}
Circle operator +(Circle C1, Circle C2)
{
return Circle(C1.Point, C1.R + C2.R);
}
Circle operator -(Circle C1, Circle C2)
{
return Circle(C2.Point, C1.R - C2.R);
}
};
int main()
{
Circle c1, c2, cr1, cr2, ck1, ck2;
// create c1
// create c2
cr1 = c1 + c2;
// display cr1
cr2 = c2 + c1;
// display cr2
ck1 = c1 - c2;
// display ck1
ck2 = c2 - c1;
// display ck2
return 0;
}
Two classes Point and Circle, where Circle have member of Point as it's center, two operators to add and to subtract two Circles.
And I can't compile this, what is wrong?
#################################################################################
EDIT:
After correction it looks like that, and works perfectly:
#include <iostream>
using namespace std;
class Point
{
public:
double X, Y;
Point(){}
Point(double x, double y)
{
X = x;
Y = y;
}
};
class Circle
{
public:
double R;
Point P;
Circle(){}
Circle(Point p, double b)
{
P = p;
R = b;
}
Circle operator+(const Circle& C1)
{
Circle C;
C.P = this->P;
C.R = this->R + C1.R;
return C;
}
Circle operator -(const Circle& C1)
{
Circle C;
C.P = C1.P;
C.R = this->R - C1.R;
return C;
}
};
int main()
{
double X, Y, R;
cout << "Coordinates for C1:" << endl;
cout << "\tX: ";
cin >> X;
cout << "\tY: ";
cin >> Y;
cout << "Radius for C1:";
cin >> R;
Circle *c1 = new Circle(Point(X, Y), R);
cout << "Coordinates for C2:" << endl;
cout << "\tX: ";
cin >> X;
cout << "\tY: ";
cin >> Y;
cout << "Radius for C2:";
cin >> R;
Circle *c2 = new Circle(Point(X, Y), R);
Circle cs1 = c1->operator+(*c2);
Circle cs2 = c1->operator-(*c2);
Circle cr1 = c2->operator+(*c1);
Circle cr2 = c2->operator-(*c1);
cout << "cs1([" << cs1.P.X << ", " << cs1.P.Y << "], " << cs1.R << ")" << endl;
cout << "cs2([" << cs2.P.X << ", " << cs2.P.Y << "], " << cs2.R << ")" << endl;
cout << "cr1([" << cr1.P.X << ", " << cr1.P.Y << "], " << cr1.R << ")" << endl;
cout << "cr2([" << cr2.P.X << ", " << cr2.P.Y << "], " << cr2.R << ")" << endl;
char ch;
cin >> ch;
return 0;
}
When you define operators like operator- inside your class as member functions, then when you use it
C3 = C1 + C2;
The compiler is actually calling your member function like
C3 = C1.operator+(C2);
From this you should be able to figure out that operators as member functions only takes one argument, and that the first object in the operator is the this object.
For stand-alone (non-member) functions they need two arguments.
You might want to check e.g. this reference on operator overloading.
You have incorrect overloaded operators. Look at the following code:
Circle operator +(const Circle& C)
{
return Circle(this->P, this->R + C.R);
}
Circle operator -(const Circle& C)
{
return Circle(this->P, this->R - C.R);
}