I wanted to declare a constructor but I face this error. As it's obvious , I wanted to create a program to show the polar form of a complex number. I know it's kind of ridiculous and it's easier to do this , with functions . BUT this is a project and it is mentioned not to change the body of main function.
How can this be fixed?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
class Complex
{
public:
double real , img;
Complex()
{
real = 0;
img = 0;
}
};
class constructComplex : public Complex
{
public:
constructComplex(double a , double b)
{
real = a;
img = b;
}
};
class printPolarForm : public Complex
{
public:
printPolarForm(Complex z)
{
cout << fixed << setprecision(2);
double r = sqrt( z.real * z.real + z.img * z.img );
double argument = atan2(z.img , z.real)*180/3.14;
cout << r << "e^(i" << argument << ')';
}
};
int main()
{
cout << fixed << setprecision(2);
double x1, y1;
cin >> x1 >> y1;
Complex c = constructComplex(x1, y1);
printPolarForm(c);
return 0;
}
You have a serious misunderstanding of what classes are for. Generally speaking classes encapsulate some state, i.e. member variables, and some operations on that state. None of your last two classes above have any state beyond the Complex class that they inherit from, so they should not exist as classes.
Let's see how this code should be written
constructComplex is an attempt to construct a complex number from parameters, so it should be an alternate constructor within the Complex class. i.e.
class Complex
{
public:
double real , img;
Complex()
{
real = 0;
img = 0;
}
Complex(double a, double b)
{
real = a;
img = b;
}
};
With this new constructor your main code changes from
Complex c = constructComplex(x1, y1);
to
Complex c(x1, y1);
printPolarForm is an operation on an existing complex number. It could be defined as a member function or a free function. I'll show that as a free function first
void printPolarForm(Complex z)
{
cout << fixed << setprecision(2);
double r = sqrt( z.real * z.real + z.img * z.img );
double argument = atan2(z.img , z.real)*180/3.14;
cout << r << "e^(i" << argument << ')';
}
the alternative is to make is a member function of the Complex class
class Complex
{
...
void printPolarForm() const
{
cout << fixed << setprecision(2);
double r = sqrt( real * real + img * img );
double argument = atan2(img , real)*180/3.14;
cout << r << "e^(i" << argument << ')';
}
};
The rest of the Complex class is as before. With the member function method you have to change how the function is called in main. Instead of
printPolarForm(c);
you would write
c.printPolarForm();
Either of these two options (free function or member function) are perfectly acceptable in this case. In both cases the class printPolarForm has been removed.
Related
I am trying to make a class Complex ( complex numbers of form z=a+ib m where a= _re and b=_im) and I need to create and constructor with 2 parametres(double,double). The _re and _im are 2 double pointers , and I don't know how to point them to a value. Here is the code , I can't modify the Class because is a school project .
#include <iostream>
#include <cmath>
using namespace std;
class Complex {
private:
double* _re;
double* _im;
public:
Complex();
Complex(double, double);
void Display();
};
Complex::Complex()
{
_re = 0;
_im = 0;
cout << "Complex::Complex()" << endl;
}
Complex::Complex(double re, double im)
{
double* _re = new double;
_re = &re;
double* _im = new double;
_im = &im;
cout << "Complex::Complex(double re,double im)" << endl;
}
void Complex::Display()
{
int nr = 1;
cout << "z" << nr << "= " << *_re << "+i* " << *_im << endl; nr++;
}
int main()
{
Complex z1(2,3);
z1.Display();
return 0;
}
You should update your constructor as below:
Complex::Complex(double re, double im)
{
_re = new double;
*_re = re;
_im = new double;
*_im = im;
cout << "Complex::Complex(double re,double im)" << endl;
}
note that previously when you declared double* _re = new double it was a local variable. So you never initialized the class variables _re and _im.
Better constructor definition would be to use constructor member initializer list syntax. See below:
Complex::Complex(double re, double im)
: _re(new double), _im(new double)
{
*_re = re;
*_im = im;
cout << "Complex::Complex(double re,double im)" << endl;
}
I want to declare a function in one class and run it in a different one.Below is the implementation of my class
#include <iostream>
#include <cstdlib>
#include <math.h>
using namespace std;
int myNo = 1 + rand () % 10;
class Point {
protected: int x; int y;
Point() {
x = myNo;
y = myNo;
}
float distanceBetweenMeAndAnotherPoint (Point anotherPoint){
float xyz = sqrt(pow((x-x),2) + pow((y-y),2));
return xyz;
}
};
class Circle : public Point {
private:
int radius;
Circle(int x, int y){
radius=myNo;
}
public:
printCircleInfo(){
cout << x << " " << y << " " << radius << " ";
return 1;
}Point Obj;
bool doIBumpIntoAnotherCircle (Circle anotherCircle){
if (radius + radius >=Obj.distanceBetweenMeAndAnotherPoint)
return true;
else
return false;
}
};
What should I replace Obj.distanceBetweenMeAndAnotherPoint with in order to call the function in this class?
Please provide an example in your answer. Thank you for your time.
You should use the parameter that you get, like this:
float distanceBetweenMeAndAnotherPoint (Point anotherPoint){
float dist = sqrt(pow((x-anotherPoint.x),2) + pow((y-anotherPoint.y),2));
return dist;
}
Also for the bump method, use the parameter that you get. And additionally simplify boolean return value, no need for the if-else. Resulting with something like:
bool doIBumpIntoAnotherCircle (Circle anotherCircle) {
return distanceBetweenMeAndAnotherPoint(anotherCircle)
<= (radius + anotherCircle.radius);
}
Note also that constructors should usually (though not necessarily) be public. In your case, the ctor of both classes, Point and Circle, should most likely be public and not private or protected to allow creation of objects of these types in your main.
I want to make an object of DataArea class in Area class and initialize data in main function. But the only way my code works is by initializing data in Area class.
Also, I do not know if I have made the object correctly or not. Please guide me. My code is below:
#include<iostream>
using namespace std;
class DataArea
{
public:
int radius, length, width, base, heigth;
DataArea(int l, int w, int b, int h, int r)
{
length = l;
width = w;
radius = r;
heigth = h;
base = b;
}
};
class Area
{
public:
DataArea* s = new DataArea(3, 4, 5, 6, 7);
float AreaCirle()
{
return 3.142 * s->radius * s->radius;
}
float AreaRectangle()
{
return s->length * s->width;
}
float AreaTraingle()
{
return (s->base * s->heigth) / 2;
}
};
class print_data : public Area
{
public:
void print()
{
cout << "Area of Circle is: " << AreaCirle() << endl;
cout << "Area of Rectangle is: " << AreaRectangle() << endl;
cout << "Area of Traingle is: " << AreaTraingle() << endl;
}
};
int main()
{
//DataArea da(3, 4, 5, 6, 7);
print_data m;
m.print();
}
Your DataArea is basically absolute if you do not use it outside of Area class. Similarly, print_data class can be replaced by an operator<< overload.
Following is the updated code, in which the comments will guide you through.
#include <iostream>
// DataArea (optionally) can be the part of Area class
struct DataArea /* final */
{
float length, width, base, height, radius;
DataArea(float l, float w, float b, float h, float r)
: length{ l } // use member initializer lists to initlize the members
, width{ w }
, base{ b }
, height{ h }
, radius{ r }
{}
};
class Area /* final */
{
DataArea mDataArea; // DataArea as member
public:
// provide a constructor which initialize the `DataArea` member
Area(float l, float w, float b, float h, float r)
: mDataArea{ l, w, b, h, r } // member initializer
{}
// camelCase naming for the functions and variables
// mark it as const as the function does not change the member
float areaCirle() const /* noexcept */
{
return 3.142f * mDataArea.radius * mDataArea.radius;
}
float areaRectangle() const /* noexcept */
{
return mDataArea.length * mDataArea.width;
}
float areaTraingle() const /* noexcept */
{
return (mDataArea.base * mDataArea.height) / 2.f;
}
// provide a operator<< for printing the results
friend std::ostream& operator<<(std::ostream& out, const Area& areaObject) /* noexcept */;
};
std::ostream& operator<<(std::ostream& out, const Area& areaObject) /* noexcept */
{
out << "Area of Circle is: " << areaObject.areaCirle() << "\n";
out << "Area of Rectangle is: " << areaObject.areaRectangle() << "\n";
out << "Area of Traingle is: " << areaObject.areaTraingle() << "\n";
return out;
}
int main()
{
// now construct the Area object like this
Area obj{ 3, 4, 5, 6, 7 };
// simply print the result which uses the operator<< overload of the Area class
std::cout << obj;
}
Output:
Area of Circle is: 153.958
Area of Rectangle is: 12
Area of Traingle is: 15
It seems to me that Area class is surplus for what you are trying to achieve. You should probably put methods directly in DataArea class. Then you can create as many of DataArea objects as you like...
Like this:
class DataArea
{
public:
int radius, length, width, base, heigth;
DataArea(int l , int w , int b , int h , int r )
{
length = l;
width = w;
radius = r;
heigth = h;
base = b;
}
float AreaCirle()
{
return 3.142 * radius * radius;
}
float AreaRectangle()
{
return length * width ;
}
float AreaTraingle()
{
return (base * heigth)/2;
}
};
int main(int argc, char **argv)
{
DataArea area1 (1,2,3,4,5);
DataArea area2 (8,2,3,4,5);
std::cout << area1.AreaCirle() << std::endl;
std::cout << area2.AreaCirle() << std::endl;
}
The reason why you are probably having trouble to understand the concept:
You're defining a class and instantiating an object. Sometimes these terms are used interchangeably, but in this case, this is an important distinction.
If you would like for your methods to operate on some other class, that you should make methods that accept that class as an argument. Otherwise, it is unnecessary complex.
I am trying to learn how to use c++11 user defined literals for units of physical properties. The question is, how do I avoid a mixing of these units. So that (8.0_kg + 8.0_km)--> gives error. any ideas guys? i am new to c++, be kind.
class Mass{
public:
//Mass(){
// cout << "only Mass units allowed in here" << endl;
//}
//~Mass();
long double getWeight(long double a);
double car, house, cat;
private:
long double a;
};
long double Mass::getWeight(long double w) {
cout << "returning argument: " << w << '\n'<< endl;
return 0;
}
long double operator"" _km(long double d) { return d * 1000.0; }
long double operator"" _m (long double d) {return d;}
long double operator"" _cm(long double d) { return d / 100.0; }
long double operator"" _tonne(long double m) { return m * 1000.0 ; }
long double operator"" _kg(long double m) { return m ; }
long double operator"" _lb(long double m) { return m * 0.453592; }
long double getDistance(long double d){
long double starting_d = 61.0_kg;
long double total_d = d + starting_d;
cout << "the distance I have run is: " << total_d << endl;
return 0;
}
int main() {
cout << 6.0_km << endl;
cout << 6.0_km + 3.0_m << endl;
cout << 6.0_km + 3.0_m + 15.0_cm << '\n' << endl;
cout << 8.0_tonne << endl;
cout << 8.0_km + 4.0_kg << endl;
cout << 8.0_km + 4.0_kg + 21.0_lb << '\n' << endl;
long double distance = 5.45_km;
getDistance(distance);
Mass obj1;
obj1.getWeight(13.96_lb);
cout << "This is clearly wrong: "<< 8.0_km + 4.0_kg << endl;
obj1.getWeight(10.96_km); // so is this
}
You need to define your own types, since you can't restrict what a primitive represents.
You can use a "tagged template"1 to avoid repetition of operators and such and keep it type safe.
This can be extended so you get for instance distance * distance = area or speed * time = distance checked by the compiler.
Here's a short example:
template<typename Kind>
struct Value
{
long double value;
Value& operator+= (Value v) { value += v.value; return *this; }
};
template <typename Kind>
Value<Kind> operator+ (Value<Kind> lhs, Value<Kind> rhs) { return lhs += rhs; }
// These types don't need definitions; we only need some unique type names.
struct M;
struct D;
using Mass = Value<M>;
using Distance = Value<D>;
Mass operator"" _kg(long double d) { return { d };}
Mass operator"" _lb(long double d) { return { d * 0.453592 };}
Distance operator"" _km(long double d) { return { d * 1000 };}
Distance operator"" _mile(long double d) { return { d * 1609 };}
int main()
{
// OK
Distance d = 1.2_km + 0.2_mile;
// OK
Mass m = 2.3_kg + 1.4_lb;
// invalid operands to binary expression ('Distance' (aka 'Value<D>')
// and 'Mass' (aka 'Value<M>'))
Distance d2 = 2.4_km + 1.2_kg; // Nope
}
1) I don't think there's an established term in C++, but it's very similar to what Haskell refers to as phantom types.
Create classes representing numeric values of the different units. That's how it's been done since long before C++ 11.
Custom literals can make instantiation more readable, though, because it helps preserve the usual order of number and unit :)
See http://en.cppreference.com/w/cpp/language/user_literal
class MassKg
{
double value;
// public c'tor, numeric operators, &c.
};
// ...
MassKg mass(5.0);
DistanceM distance(3.0);
auto c = mass * distance; // may yield an instance of TorqueKgM, or MomentumKgM, therefore
// explicit functions / methods are preferrable for mixed
// multiplication or division
auto mass2 = mass + MassKg(2.0); // yiels an instance of MassKg
auto invalid = mass + distance; // compile time error
I made a class Valjak (Roller), and gave it variables h (height) and r (radius) and made functions for area (Oplosje) and volume (Volumen).
I created 2 objects and now I need to overload operator + in such way that result of adding two objects from class Valjak (roller) creates a new third object that has as height equal to the height of first object plus the height of second object, and radius that is the radius of first object plus radius of third object.
This is my code so far:
#include <iostream>
#include <math.h>
using namespace std;
class Valjak{
private: float r, h;
public:
Valjak(){
r = 1;
h = 1;
}
Valjak(float rr, float hh){
r = rr;
h = hh;
}
void Oplosje(){
cout << "Oplosje valjka je: " << 2 * (pow(r, 2)*3.14) + 2 * r*h << endl;
}
void Volumen(){
cout << "Volumen je: " << (pow(r, 2)*3.14) * h << endl;
}
};
int main(){
Valjak V1;
Valjak V2(5, 10);
cout << "Vrijednosti prvog objekta!" << endl;
V1.Oplosje();
V1.Volumen();
cout << "Vrijednosti drugog objekta" << endl;
V2.Oplosje();
V2.Volumen();
system("PAUSE");
return 0;
}
First, you must write getters for r and h, let's name them get_r and get_h:
class Valjak {
// ...
public:
float get_r() { return r; }
float get_h() { return h; }
// ...
}
Then overload operator + for two objects of Valjak class:
Valjak operator+(const Valjak & a, const Valjak & b)
{
return Valjak(a.get_r() + b.get_r(), a.get_h() + b.get_h());
}