BRabbit27 BRabbit27 - 1 year ago 66
C++ Question

How to declare operator/ overload function to operate on a const variable and a non-const variable?

I have the following code

#pragma once

#include "material.h"
#include "../Math/vector.h"
#include <cmath>

class LambertianMaterial : public Material
LambertianMaterial(Vector rho);
Vector brdf(Vector wi) const
return mRho / M_PI; // Error here

Vector mRho;

In the line corresponding to the return statement of brdf I am getting the following error

Invalid operands to binary expression ('const Vector' and 'double')

In the class vector I have declared the

Vector operator/(const float a);

I was thinking of redefining the method to

friend Vector operator/(const Vector& v, const float& a);

Is this a good way of doing it or is there a way so that the current definition of the operator accounts for the
const Vector

Answer Source

You could make it a const member function, which could be applied for const and non-const object, if it won't (and it shouldn't) modify any non-static member variables.

Vector operator/(const float a) const;

As you thought, making it non-member function (and declared as friend if necessary) could do the work too. IMO I prefer to it for operator/. See Operator overloading : member function vs. non-member function? for more informations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download