[英]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
{
public:
LambertianMaterial(Vector rho);
Vector brdf(Vector wi) const
{
return mRho / M_PI; // Error here
}
private:
Vector mRho;
};
In the line corresponding to the return statement of brdf I am getting the following error 在对应于brdf的return语句的行中,我收到以下错误
Invalid operands to binary expression ('const Vector' and 'double')
In the class vector I have declared the operator/
like 在类向量中,我已经声明了
operator/
like
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
case? 这是一个很好的方法,还是有一种方法,以便运算符的当前定义考虑
const Vector
案例?
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. 你可以使它成为const成员函数,如果它不会(并且它不应该)修改任何非静态成员变量,它可以应用于const和非const对象。
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/
. IMO我更喜欢
operator/
。 See Operator overloading : member function vs. non-member function? 请参阅运算符重载:成员函数与非成员函数? for more informations.
了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.