1

したがって、Vector クラスには、ドットとクロス積の 2 つのオーバーロードされた演算子があります。これはできないと思います。代わりに、クロス関数を使用する必要があります。

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;
}

偶然にも、これを行う素晴らしい方法がありますが、それはまったく可能ですか?

4

2 に答える 2

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;
于 2012-10-31T18:09:45.290 に答える
5

You can't overload on return type.

You have a few choices:

  • Use free functions dot(v1, v2);
  • Abuse another binary operator that doesn't make sense for your class (e.g. v1 ^ v2) as the dot or cross operator (note that the precedence may not be what you want);
  • Abuse paired operators and objects to construct an appropriate syntax (e.g. v1 <dot> v2, using the < and > operators and a global dot object).
于 2012-10-31T18:13:17.323 に答える