How do I call operator function to add two objects? [duplicate] - c++

This question already has an answer here:
Overloaded Addition assignment operator in C++ for two /more than two objects?
(1 answer)
Closed 5 years ago.
Trying to develop operator == to compare two balls where two balls are considered equal if they have the same radius and operator > to compare two balls. To see if one ball has a bigger radius than another one, for let's say ball x is > than another ball y. += to add the volume of the right-side-operand to the volume of the left-side-operand. It is like to melt two metal balls to make one metal ball. The new ball's radius is cube root of (r1^3 + r2^3). Wish to use pow() function to calculate the cube value and cube root value. operator + to add the two balls together and return a new ball. The size of the new ball is the sum of the size of the two operands connected by the +.
In the main() function, couldn't add ball m(10) with ball n(20) to create another ball d, like d = m+n.
int main()
{
//use ball
ball x; float re;
//radius of ball y is set to 10
ball y(10);
//asks for radius of x?
cout << "Enter radius for ball x: ";
cin >> re;
//sets the radius of x
x.set_radius(re);
ball m(10);
ball n(20);
ball d;
d = m + n;
//cout << "The radius of ball d is " << m.;
system("pause");
return 0;
}
//ball.h
{
class ball
{
public:
//sets the intial raduis to 0
ball() {
radius = 0;
}
ball(float radii) {
radius = radii;
}
float get_radius() {
return radius;
}
void set_radius(float redly) {
radius = redly;
}
bool operator == (ball x) {
if (radius == x.radius)
return true;
else
return false;
}
bool operator > (ball x) {
if (radius > x.radius)
return true;
else
return false;
}
bool operator += (ball x) {
radius += x.radius;
}
ball operator + (ball a, ball b) {
ball d;
d += a;
d += b;
return d;
}
private:
float radius;
};
}
#endif

If you are only looking for (x_volume/ y_volume)% and (x_surfacearea/y_surfacearea)%
I suggest doing :
float vol_over_y() {
float v;
v = ((radius * radius * radius)/(10*10*10));
return v;
}
float sa_over_y() {
float a;
a = (radius * radius /(10*10));
return a;
}
because other constants like (4.0/3.0)* 3.14 in volume and 3.14 in surface area cancel out.
If in case y changes,
float vol_over_y(float y_rad) {
float v;
v = ((radius * radius * radius)/(y_rad*y_rad*y_rad));
return v;
}
float sa_over_y(float y_rad) {
float a;
a = (radius * radius /(y_rad*y_rad));
return a;
}

You thought too much. It is simply a little tweak in your main logic:
ball x;
ball y(10);
// your code to construct x
cout << "The volume of x is " << ( x.volume() / y.volume() )<< "% of the volume of y."<< endl;
// similar for surface area, try it out yourself
If in case you really need to do it in a method(which is quite ridiculous imho), you should just pass the other ball in and calculate:
float volume_ratio_to(const ball& base) {
return volume() / base.volume();
}
And your main logic become
cout << "The volume of x is " << x.volume_ratio_to(y) << "% of the volume of y."<< endl;
Edited for your updated question:
The reason why + operator does not work for you is because you didn't overloaded the operator right.
If you want it to be member of ball, the + operator should only takes one argument.
i.e. looks like:
class ball {
//....
ball operator + (ball another);
}
Or, don't make it member of ball:
// outside ball class
ball operator + (ball a, ball b) {....}
Refer to Overloaded Addition assignment operator in C++ for two /more than two objects? for more detailed description on how to overload addition operator.
There are quite a lot of other problems in your code too
You should have passed balls to methods by reference instead of by value
You should have considered adding const in various places
You += logic is totally wrong. Pay attention to what you quoted:
+= to add the volume of the right-side-operand to the volume of the
left-side-operand. It is like to melt two metal balls to make one
metal ball. The new ball's radius is cube root of (r1^3 + r2^3)

//This helps
int main()
{
//use ball
ball x; float re;
ball y(10);
cout << "Enter radius for ball x: " << endl;
cin >> re;
x.setl(re);
cout << "The volume of x is " << (x.volume()/y.volume())*100 << "%
of the volume of y."<< endl;
cout << "The surfacearea of x box is " <<
(x.surface_area()/y.surface_area())*100 << "% of
the surfacearea of y." << endl;
system("pause");
return 0;
}
//ball.h
#pragma once
#ifndef Ball
#define Ball
namespace bsize
{
class ball
{
public:
ball(){
radius = 0;
}
ball(float radii) {
radius = radii;
}
float volume() {
float v;
v = ((4.0/3.0)* 3.14 * (radius * radius * radius));
return v;
}
float surface_area() {
float a;
a = (4 * 3.14 * radius * radius);
return a;
}
float get_radius(){
return radius;
}
void set_radius(float redly) {
radius = redly;
}
private:
float radius;
};
}
#endif

Related

calculation of the midpoint of the coordinate values entered by the user. (x, y, z axes) Need class topic

I have an assignment, here is the description:
Create a class named Point. It must have three private float field named as x, y, z to keep coordinates in space and public get and set functions to access these data members ( getX(), getY(), getZ(), setX(), setY(), setZ() ). Create another function that is defined outside of the scope of Point class and named Space. In Space function, you will find the middle point between two points and create a new Point object that will keep calculated coordinates. The written code below must be able to run without errors.
The teacher gave us structure of the code. The code should be like below. only the definition of get, set and space functions can change. I wrote the set and get functions, but I have no idea what to do with the space function. That's why I need help with the space function part.
#include <iostream>
using namespace std;
class Point {
private:
int x, y, z;
public:
float getX();
float getY();
float getZ();
void setX(float x1);
void setY(float y1);
void setZ(float z1);
};
float Point::getX() {
return x;
}
float Point::getY() {
return y;
}
float Point::getZ() {
return z;
}
void Point::setX(float x1) {
x = x1;
}
void Point::setY(float y1) {
y = y1;
}
void Point::setZ(float z1) {
z = z1;
}
Point Space(Point a, Point b)
{
// complete space function
}
int main()
{
float x_, y_, z_;
Point p[3];
for (int i = 0; i < 2; ++i)
{
cout << "Please enter x coordinate for p" << i + 1 << endl;
cin >> x_;
p[i].setX(x_);
cout << "Please enter y coordinate for p" << i + 1 << endl;
cin >> y_;
p[i].setY(y_);
cout << "Please enter z coordinate for p" << i + 1 << endl;
cin >> z_;
p[i].setZ(z_);
}
p[2] = Space(p[0], p[1]);
cout << "Coordinations of middle point (p3) between p1 and p2 is x=" << p[2].getX() << ",y=" << p[2].getY() << ", z=" << p[2].getZ();
return 0;
}
As the instructions says:
In Space function, you will find the middle point between two points and create a new Point object that will keep calculated coordinates.
Per Mid Point Formula in 3D:
A midpoint is the exact center point between two defined points. To find this center point, midpoint formula is applied. In 3-dimensional space, the midpoint between (x1, y1, z1) and (x2, y2, z1) is (x1+x2)/2, (y1+y2)/2, (z1+z2)/2.
So, try this:
Point Space(Point a, Point b)
{
Point mid;
mid.setX((a.getX() + b.getX()) / 2);
mid.setY((a.getY() + b.getY()) / 2);
mid.setZ((a.getZ() + b.getZ()) / 2);
return mid;
}

"Undefined symbol" error with my functions when using classes

I'm writing a program that calculates the area and diameter using classes and functions. My issue is that I'm getting an undefined symbol error with my functions. I'm sure it's probably an easy fix ... I just can't figure it out.
(Writing the code on a mac)
Here's the code:
#include<iostream>
using namespace std;
class Circle
{
public:
int radius;
void printArea();
void printDiameter();
};
void Circle::printArea()
{
double area;
area = radius * radius * 3.14159;
cout<<"A circle with radius "<<radius<<" has an area of "<<area<<endl;
}
void Circle::printDiameter()
{
int diam;
diam = radius * 2;
cout<<"A circle with radius "<<radius<<" has a diameter of "<<diam<<endl;
}
int main()
{
void printArea(Circle);
void printDiameter(Circle);
Circle aBigCircle, aLittleCircle;
aBigCircle.radius = 50;
aLittleCircle.radius = 4;
printArea(aBigCircle);
printDiameter(aBigCircle);
printArea(aLittleCircle);
printDiameter(aLittleCircle);
}
The printArea() and printDiameter() methods are encapsulated within the Circle class, so you must call them from an object.
#include<iostream>
using namespace std;
class Circle
{
public:
int radius;
void printArea();
void printDiameter();
};
void Circle::printArea()
{
double area;
area = radius * radius * 3.14159;
cout<<"A circle with radius "<< radius <<" has an area of "<< area << endl;
}
void Circle::printDiameter()
{
int diam;
diam = radius * 2;
cout<<"A circle with radius "<< radius <<" has a diameter of " << diam << endl;
}
int main()
{
Circle aBigCircle, aLittleCircle;
aBigCircle.radius = 50;
aLittleCircle.radius = 4;
aBigCircle.printArea();
aBigCircle.printDiameter();
aLittleCircle.printArea();
aLittleCircle.printDiameter();
return 0;
}
Result:
A circle with radius 50 has an area of 7853.97
A circle with radius 50 has a diameter of 100
A circle with radius 4 has an area of 50.2654
A circle with radius 4 has a diameter of 8
int main()
{
// delete printArea() and printDiameter() lines
// void printArea(Circle);
// void printDiameter(Circle);
Circle aBigCircle, aLittleCircle;
aBigCircle.radius = 50;
aLittleCircle.radius = 4;
aBigCircle.printArea();
aBigCircle.printDiameter();
aLittleCircle.printArea();
aLittleCircle.printDiameter();
}
Delete printArea() and printDiameter() declare in main(). It should fix your problem.

C++ how to find area of square or rectangle with vector of coordinates

How do I find the area of square or rectangle assuming user has entered some accurate points to form a square or rectangle.
I need to calculate the area inside the square class and rectangle class respectively.
I have 2 vector of coordinates, coordX and coordY.
My idea is when either or x or y has same value it will be a line and I can find the distance x2 but I'm not sure how to implement it in code.
double Square::computeArea() {
double area;
for (int x = 0; x < coordX.size; x++) {
for (int y = 0; y < coordY.size; y++) {
if (coordX[x] == coordY[y])
{
//....
}
}
}
return area;
}
This is how i populate my vector with user input
Square Square;
for ( int i = 1; i <= 4; i++) {
cout << "Please enter x-coordinate of pt " << i << ": ";
cin >> x;
Square.setXCoordinate(x);
cout << "Please enter y-coordinate of pt " << i << ": ";
cin >> y;
Square.setYCoordinate(y);
}
this is my mutator function in my class. Square inherit from ShapeTwoD
void ShapeTwoD::setXCoordinate(int x) {
coordX.push_back(x);
}
void ShapeTwoD::setYCoordinate(int y) {
coordY.push_back(y);
}
No need for square root.
Take two edges from one vertex, rotate one by 90°, take dot product.
double dx1 = coordX[3] - coordX[0];
double dy1 = coordY[3] - coordY[0];
double dx2 = coordX[1] - coordX[0];
double dy2 = coordY[1] - coordY[0];
double area = abs(dx1*dy2 - dy1*dx2)
As a bonus, this will calculate the correct area for all parallelograms, not just rectangles.
This assumes, the points are entered in clockwise or couter-clockwise order. If that's not the case, find out which point has the greatest distance to point[0] then discard it and use the other two instead of 1 and 3 above.
Assuming your coordinates are something like
// 3-----------2
// | |
// | |
// 0-----------1
Then you could do
#include <cmath>
double distance(double x1, double x2, double y1, double y2)
{
return std::sqrt(std::pow(x2 - x1, 2) + std::pow(y2 - y1, 2));
}
double Square::computeArea() const
{
double length = distance(coordX[0], coordX[1], coordY[0], coordY[1]);
double width = distance(coordX[0], coordX[3], coordY[0], coordY[3]);
return length * width;
}
This allows your rectangle to be at any arbitrary orientation, instead of x-y axis aligned. You just need to maintain a convention of the indexes of the corners, like in my example diagram.

finding the edge connection point between two AABB area

Lets say I have two AABB based areas, each area defined by two coordinates mins{x, y} and maxs{x, y}, I want to find the middle connection point between them.
Since my english is not good, I can't explain all with my words,
see the following picture for easier understanding:
http://i.*.com/WokivEe.png
All I need to find is the red point coordinates.
so If we move this into programming question, actual data structures would look like this:
struct Vec2D {
float x, y;
}
struct Rectangle {
Vec2D min;
Vec2D max;
}
Rectangle obj[2]
Anyone got an idea for an algorithm?
Along either the X or Y axis, sort the coordinates of the sides that touch into order. Then average the 2nd and 3rd ones in that list to find their midpoint. I hope this answers the question sufficiently.
Here is a little algorithm that first find which sides of the objects are closest, and then uses the 4 points along the common side to make a list, sorted along the common axis. The average of the 2 middle points of the sorted list are the answer. This will work for both horizontal and vertical sides. I added accessor functions to the data structures so that they can be indexed; e.g., for a Vec2D, coordinate(0) is the x value and coordinate(1) is the y value.
#include <math.h>
#include <iostream>
#include <limits>
struct Vec2D {
float x, y;
float coordinate(int axis)
{
return (axis & 1) ? y : x;
}
};
struct Rectangle {
Vec2D min;
Vec2D max;
Vec2D corner(int j)
{
return (j & 1) ? max : min;
}
// Get the other corner along the given axis
Vec2D along(int j, int ax)
{
Vec2D p = corner(j);
if (0 == ax)
{
p.x = corner(1-j).x;
}
else
{
p.y = corner(1-j).y;
}
return p;
}
};
using namespace std;
inline Vec2D* vp(const void* p)
{
return (Vec2D*) p;
}
static int compare_x(const void*a, const void*b)
{
if (vp(a)->x < vp(b)->x)
{
return -1;
}
else
if (vp(a)->x > vp(b)->x)
{
return 1;
}
return 0;
}
static int compare_y(const void*a, const void*b)
{
if (vp(a)->y < vp(b)->y)
{
return -1;
}
else
if (vp(a)->y > vp(b)->y)
{
return 1;
}
return 0;
}
int main(void) {
int ax; // axis index
int c0, c1;
float gap = numeric_limits<float>::max();
struct Rectangle obj[2] = {0,2,10,10,10,5,15,20};
struct
{
int ax,c0,c1;
} closest;
// Find out which sides are the closest to each other
for(ax = 0; 2 > ax; ++ax) // Look at x axis and y axis
{
for(c0 = 0; 2 > c0; ++c0) // Look at both corners of obj[0]
{
for(c1 = 0; 2 > c1; ++c1) // Look at both corners of obj[1]
{
float dist = fabs(obj[0].corner(c0).coordinate(ax) - obj[1].corner(c1).coordinate(ax));
if (dist < gap)
{
gap = dist;
closest.ax = ax;
closest.c0 = c0;
closest.c1 = c1;
}
}
}
}
int other = 1 - closest.ax; // The other axis
cout << "The closest gap is along the " << (closest.ax ? 'y' : 'x') << " axis\n";
cout << "The common side is along the " << (other ? 'y' : 'x') << " direction\n";
// Make a list of the 4 points along the common side
Vec2D list[4];
list[0] = obj[0].corner(closest.c0);
list[1] = obj[0].along(closest.c0, other);
list[2] = obj[1].corner(closest.c1);
list[3] = obj[1].along(closest.c1, other);
// Sort them into order along the common axis
qsort(list, 4, sizeof(Vec2D), closest.ax ? compare_x : compare_y);
// Get the average of the 2 middle points along the common axis.
Vec2D answer = {
(list[1].x + list[2].x) / 2,
(list[1].y + list[2].y) / 2
};
cout << "(" << answer.x << "," << answer.y << ")\n";
}

I need to understand the top function, more specific then i already know. The bottom function is pretty much self-explanatory

bool isOnPerimeter - function that I need help with.
bool isOnPerimeter(int row, int column, int radius)
{
double dRow=static_cast<double>(row);
double dColumn=static_cast<double>(column);
double dRadius=static_cast<double>(radius);
if (pow(dRow,2.0)+pow(dColumn,2.0)<=pow(dRadius,2.0) &&
pow(dRow,2.0)+pow(abs(dColumn)+1,2.0) > pow(dRadius,2.0))
return true;
else
return false;
}
void drawCircle(int radius)
{
for (int row = -radius;row <= radius;++row)
{
for (int column = -radius;column <= radius;++column)
{
if (isOnPerimeter(row,column,radius))
cout << "*";
else
cout << " ";
cout << endl;
}
}
}
the function looks like it's drawing a circle inside the square define by coordinates (-radius,-radius), (radius,radius).
How it does that: consider the trigonometric circle, you know that sin^2 + cos^2 = R^2. Since sin and cos are the projections of R on oy and ox axes, all the points inside the circle have the property that sin^2 + cos^2 < R^2 and all the points outside the circle have the property sin^2 + cos^2 > R^2
In your example you row, col are the equivalent of sin, cos. So you determine the edge of the circle as being all the points for which
sin^2 + cos^2 <= R^2 && sin^2 + (cos+1)^2 > R^2
Hope this helps