如何实现在实例之前可用的运算符(前置位置)
我有一个带有 operator*
的类,它以标量作为参数,它允许我执行类实例与标量的乘法。我希望能够将标量乘以我的类的实例(具有相同结果的相反顺序)。我怎样才能做到这一点?
这是一个例子:
class Vector3d
{
public:
Vector3d(double x, double y, double z) {
v[0] = x; v[1] = y; v[2] = z;
}
template<typename T>
Vector3d operator*(const T s) const {
return( Vector3d( v[0] * s, v[1] * s, v[2] * s));
}
//protected: example purpose
double v[3];
};
main()
{
double scalar = 2.0;
Vector3d vector(1.0,2.0,3.0);
Vector3d v2 = vector*scalar;
//This is the operation I want to be able to perform !
//Vector3d v3 = scalar*vector;
return 0;
}
我尝试像使用 ostream<<
运算符一样实现它,但没有成功......
template<typename T>
Vector3d operator*(T& s, const Vector3d &v)
{
return( Vector3d( v[0] * s, v[1] * s, v[2] * s));
}
I have a class with the operator*
taking a scalar as argument, that allow me to perform the multiplication of an instance of my class with a scalar. I'd like to be able to multiply a scalar by an instance of my class (inverse order with the same result). How can I do that ?
Here an example :
class Vector3d
{
public:
Vector3d(double x, double y, double z) {
v[0] = x; v[1] = y; v[2] = z;
}
template<typename T>
Vector3d operator*(const T s) const {
return( Vector3d( v[0] * s, v[1] * s, v[2] * s));
}
//protected: example purpose
double v[3];
};
main()
{
double scalar = 2.0;
Vector3d vector(1.0,2.0,3.0);
Vector3d v2 = vector*scalar;
//This is the operation I want to be able to perform !
//Vector3d v3 = scalar*vector;
return 0;
}
I tried to implement it like we do with ostream<<
operator without success ...
template<typename T>
Vector3d operator*(T& s, const Vector3d &v)
{
return( Vector3d( v[0] * s, v[1] * s, v[2] * s));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须将您的运算符 * 声明为具有相反参数顺序的非成员函数(外部类),并从中调用另一个函数
并且不要忘记指定模板参数:
还有一个问题...为什么要采用
T&
T& code> 而不是const T&
或者只是T
?在当前形式中,您正在阻止传递右值。例如,这不会编译:You must declare your operator* as a nonmember function (outside class) with inverse argument order and call the other one from it
And don't forget specifying the template parameters:
One more issue... Why take
T&
istead ofconst T&
or justT
? In current form you're preventing rvalues to be passed. For example, this wouldn't compile:最好在类之外进行运算符重载,这样可以提供最大的灵活性。
// 这编译得很好。
It is best to do operator overloading outside of the class, that gives you maximum flexibility.
// This compiles fine.