Bar*_*hor 1 c++ overloading operators
所以我有我的Vector类,点和交叉产品的这两个重载运算符,我假设你不能这样做,我应该有一个交叉函数.
inline T operator *(const Vector3<T> &v)
{
return value[0]*v[0]+value[1]*v[1]+value[2]*v[2];
}
inline Vector3<T> operator *(const Vector3<T> &v)
{
Vector3<T> result;
result[0] = value[1]*v[2] - value[2]*v[1];
result[1] = value[2]*v[0] - value[0]*v[2];
result[2] = value[0]*v[1] - value[1]*v[0];
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果有机会,有一种方法可以做到这一点很棒,是不是很有可能?
小智 6
简短的回答:不可能
答案很长:你可以做点什么
template<class T>
class Product
{
public:
Product (const Vector3<T> &v1, const Vector3<T> &v2)
: v1_ (v1), v2_(v2) {}
operator T () const {/*calc and return a dot product*/}
operator Vector3<T> () const {/*calc and return a cross product*/}
private:
const Vector3<T> &v1_;
const Vector3<T> &v2_;
};
template<class T>
class Vector3
{
...
public:
inline Product<T> operator *(const Vector3<T> &v)
{
return Product<T> (*this, v);
}
};
// usage
Vector3<int> v1 = {...};
Vector3<int> v2 = {...};
int dot = v1 * v2;
Vector3<int> cross = v1 * v2;
Run Code Online (Sandbox Code Playgroud)
您不能在返回类型上重载.
你有几个选择:
dot(v1, v2);v1 ^ v2)作为点或交叉运算符(注意优先级可能不是你想要的);v1 <dot> v2,使用<和>运算符和全局dot对象).