In: Computer Science
class Point3d { public: Point3d(double x, double y, double z);
Point3d(const point3d& p);
void setX(double x);
void setY(double y);
void setZ(double z);
double getX() const;
double getY() const;
double getZ() const;
point3d& operator=(const point3d& rhs); private: double x; double y; double z;
};
Given the Point class above, complete the following:
1. Write just the signature for the overloaded addition operator that would add the respective x,y, and z from two point3d objects.
2. What is the output of the code (assuming copy constructor and copy assignment operators are properly implemented).
point3d p1{3,4,5};
point3d p2{p1};
p2.setY(2*p2.getX());
point3d* p3 = new point3d{p1.getX(), p2.getY(), p2.getZ()};
p3 = &p1; cout << *p3.getZ() << endl;
p1.setY(2*p1.getZ());
p3.setX(p2.getZ());
p1 = p2; cout << p1.getX() + “, ” p1.getY() + “, ” p1.getZ() << endl;
cout << p2.getX() + “, ” p2.getY() + “, ” p2.getZ() << endl;
cout << p3.getX() + “, ” p3.getY() + “, ” p3.getZ() << endl;
delete p3;
Given code:
.
class Point3d
{
public:
Point3d(double x, double y, double z);
Point3d(const Point3d &p);
void setX(double x);
void setY(double y);
void setZ(double z);
double getX() const;
double getY() const;
double getZ() const;
Point3d &operator=(const Point3d &rhs);
private:
double x;
double y;
double z;
};
.
Q->1. Write just the signature for the overloaded addition
operator that would add the respective x,y, and z from two Point3d
objects.
Answer:
Point3d &operator+(const Point3d other);
.
Q->2. What is the output of the code (assuming copy constructor and copy assignment operators are properly implemented).
Point3d p1{3, 4, 5};
Point3d p2{p1};
// p1 and p2 are both same points (3,4,5) till this line
// set p2.y = 2 * 3 = 6
p2.setY(2 * p2.getX());
// now p2 will be (3,6,5)
Point3d *p3 = new Point3d{p1.getX(), p2.getY(), p2.getZ()};
// p3 points to (3,6,5) till this line
p3 = &p1;
// p3 will be same as p1 due to above line ie (3,4,5)
cout << (*p3).getZ() << endl;
// prints 5
p1.setY(2 * p1.getZ());
// above line sets p1.y = 2 * 5 = 10
// now p1 is (3,10,5)
p3->setX(p2.getZ());
// above line sets p3.x = 5, it also modifies p1
// now p3 will be (5,4,5)
p1 = p2;
// now p1 = p2 = (3,6,5)
// and p3 points to p1, it also points to (3,6,5)
// print all points
cout << p1.getX() + ", " p1.getY() + ", " p1.getZ() << endl;
cout << p2.getX() + ", " p2.getY() + ", " p2.getZ() << endl;
cout << p3.getX() + ", " p3.getY() + ", " p3.getZ() << endl;
// above lines prints:
// 3, 6, 5
// 3, 6, 5
// 3, 6, 5
delete p3;
.
Final output through running program::
.