Hi! I thought if I have overloaded the + operator so that it calculates the area of n number circles that are added, is there a way to make it calculate the circumference also?
Can I tell C++ and somehow choose if I want to use the + operator to calculate area or the circumference of the circles? Or is this absolutely impossible to achieve?
Like this:
Add area of two circles: totArea = circle1 + circle2
Add circumference of two circles: totCircum = circle1 + circle2
Shape.h
Code:
#ifndef SHAPE_H
#define SHAPE_H
#include <string>
using namespace std;
class Shape {
protected:
int x, y;
public:
Shape(int x, int y);
Shape();
virtual ~Shape();
virtual double area() const = 0;
virtual double circumference() const = 0;
virtual string toString() const = 0;
};
#endif
Shape.cpp
Code:
#include "Shape.h"
Shape::Shape(int x, int y)
{
this->x = x;
this->y = y;
}
Shape::Shape()
{
}
Shape::~Shape()
{
}
Circle.h
Code:
#ifndef CIRCLE_H
#define CIRCLE_H
#include "Shape.h"
class Circle : public Shape {
public:
enum CALC {AREA, CIRCUMFERENCE};
private:
static const double PI;
double radius;
public:
Circle(int x, int y, double radius);
virtual ~Circle();
double area() const;
double circumference() const;
virtual string toString() const;
double operator+(const Circle& circle);
};
#endif
Circle.cpp
Code:
#include "Circle.h"
const double Circle::PI = 3.14159;
Circle::Circle(int x, int y, double radius)
:Shape(x, y)
{
this->radius = radius;
}
Circle::~Circle()
{
}
double Circle::area() const
{
return this->PI * this->radius * this->radius;
}
double Circle::circumference() const
{
return 2 * this->PI * this->radius;
}
string Circle::toString() const
{
return "X: " + to_string(this->x) +
"\nY: " + to_string(this->y) +
"\nRadius: " + to_string(this->radius);
}
double Circle::operator+(const Circle& circle)
{
return (this->area() + circle.area());
}
Testing.cpp
Code:
#include <iostream>
#include "Shape.h"
#include "Circle.h"
using namespace std;
int main() {
Shape* circle = new Circle(10, 10, 5.2);
Circle c1(2, 2, 10);
Circle c2(3, 3, 4);
double sum = c1 + c2;
cout << circle->toString() << endl;
cout << "\nArea of two circles: " << sum << endl;
delete circle;
getchar();
return 0;
}