Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloading an operator double * Vec

I'm trying to make a Vec class to represent a set of 3 doubles, x, y, z, respectively. What I would like to do is make it so that I can multiply a scalar times the vector and have it multiply each component.

I have been able to get it to work when I mutliply a vector by a scalar, but not when I do the reverse. For example, the following works:

Vec a = Vec(1.0, 1.0, 1.0);
Vec b = a * 2.0;

But, whenever I try to multiply a scalar by a vector, it doesn't work. Ideally the command would look like this:

Vec a = Vec(1.0, 1.0, 1.0);
Vec b = 2.0 * a;

Here is the code I've done so far:

#include "Vec.h"
#include <limits>
#include <cmath>
#include "constants.h"
#include <iostream>
#include <string>

double Vec::angle( const Vec & vec) {
    return acos((this->dot(vec))/(this->mag() * mag()));
}

double Vec::angle_d(const Vec & vec) {
    return (angle(vec) * _PI / 180.0);
}

double Vec::angle_r(const Vec & vec)    {
    return this->angle(vec);
}

Vec Vec::cross( const Vec& vec) {
    return Vec( (y * vec.z - z * vec.y),
            (z * vec.x - x * vec.z),
            (x * vec.y - y * vec.x));
}

double Vec::dot( const Vec & vec)   {
    return (x * vec.x + y * vec.y + z * vec.z);
}

double Vec::mag()   {
    return std::sqrt(x*x + y*y + z*z);
}

Vec Vec::operator=(const Vec& rhs)  {
    return Vec(rhs);
}

Vec Vec::operator*(const Vec& rhs)  {
    return Vec( x * rhs.x, y * rhs.y, z * rhs.z);
}

Vec Vec::operator*(const double rhs)    {
    return Vec(rhs * x, rhs * y, rhs * z);
}

Vec::Vec()  : 
    x(std::numeric_limits<double>::signaling_NaN()),
    y(std::numeric_limits<double>::signaling_NaN()),
    z(std::numeric_limits<double>::signaling_NaN()) {   }

Vec::Vec( double c) :
    x(c), y(c), z(c)    {}

Vec::Vec(const Vec & vec)   : 
    x(vec.x), y(vec.y), z(vec.z)    {   }

Vec::Vec(double a, double b, double c)  
    : x(a), y(b), z(c)  {   }
like image 655
HardcoreBro Avatar asked Apr 14 '26 18:04

HardcoreBro


1 Answers

You need a global operator that takes two arguments: a double and then a Vec, and it can be easily implemented by calling the operator you already have listed

inline Vec operator*(double s, const Vec& v) {
    return v * s;
}
like image 110
ctrl_phil Avatar answered Apr 17 '26 11:04

ctrl_phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!