-1

Imagine you have the following code:

Vector3D class{
   public:
      Vector3D(double=0, double=0, double=0);
      Vector3D(const Vector3D& v){x = v.x;y = v.y;z = v.z;}
   private:
      double x,y,z;
}

And I wanna add two vectors:

Vector3D a(1,2,1);
Vector3D b(2,4,2);
Vector3D c = a + b;

How can I do that without modifying neither of them... I thought of this:

Vector3D class{
   public:
      Vector3D(double=0, double=0, double=0);
      Vector3D(const Vector3D& v){x = v.x;y = v.y;z = v.z;}
      Vector3D(const Vector3D& v, const Vector3D& f){
          x = v.x + f.x;
          y = v.y + f.y;
          z = v.z + f.z;
     }
   private:
      double x,y,z;
}

However, this error appears... "error: ‘Vector3D& Vector3D::operator+(const Vector3D&, const Vector3D&)’ must have either zero or one argument ..." I know that I can only add one argument to the method within a class, but how can I work around this issue in order to add these two vectors without modfying neither?

Thank you in advance!

1 Answers1

0

You created a constructor that takes two Vector3D:

Vector3D(const Vector3D& v, const Vector3D& f)

so you can use that:

Vector3D c(a, b);

An alternative way is defining operator+ in your class Vector3D like this:

Vector3D operator+(const Vector3D& other) const {
    return Vector3D(x + other.x, y + other.y, z + other.z);
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70