?
pyhax schrieb:
Das mit der Basis Klasse habe ich schon probiert. Problem:
Ich möchte ja in Subtract, Add, ... einen Vektor und keinen VektorBase zurückgeben. Wenn ich aber dann schreibe
template <unsigned int n>
Vektor& VektorBase<n>::operator/=(float x) {
// ...
return *this;
}
geht das ja nicht ...
Vererben, dazu ein paar freie Funktionen. Funktioniert schon.
Aber naja, ich habe seit Jahren kein C++ mehr programmiert ... hoffe mal es ist nicht zu katastrophal
#include <iostream>
//using namespace std;
#ifndef VECTORN_H
#define VECTORN_H
namespace Mathematics
{
template<typename T, int N>
class Vector;
template<typename T, int N>
class VectorBase
{
protected:
T data[N];
VectorBase()
: data()
{}
public:
T Sum() const;
T& operator[](int index);
const T& operator[](int index) const;
template<typename T, int N>
friend Vector<T,N>& operator+=(Vector<T,N>& a, Vector<T,N> const& b);
};
template<typename T, int N>
T VectorBase<T,N>::Sum() const
{
T sum = 0;
for(int i=0; i<N; ++i)
sum+=data[i];
return sum;
}
template<typename T, int N>
T& VectorBase<T,N>::operator[](int index)
{
return data[index];
}
template<typename T, int N>
const T& VectorBase<T,N>::operator[](int index) const
{
return data[index];
}
template<typename T, int N>
std::ostream& operator<<(std::ostream& out, VectorBase<T,N> const& vec)
{
out<<"(";
for(int i=0;i<N;++i)
out<<vec[i]<<(i<N-1?",":")");
return out;
}
template<typename T, int N>
class Vector : public VectorBase<T,N>
{
public:
Vector()
{}
};
template<typename T>
class Vector<T,3> : public VectorBase<T,3>
{
public:
T& X;
T& Y;
T& Z;
Vector()
: X(this->data[0]), Y(this->data[1]), Z(this->data[2])
{}
Vector(T x, T y, T z)
: X(this->data[0] = x), Y(this->data[1] = y), Z(this->data[2] = z)
{}
static Vector<T,3> Cross(const Vector<T,3>& a, const Vector<T,3>& b)
{
return Vector (
a.Y*b.Z - a.Z*b.Y,
a.Z*b.X - a.X*b.Z,
a.X*b.Y - a.Y*b.X
);
}
};
template<typename T, int N>
Vector<T,N>& operator+=(Vector<T,N>& a, Vector<T,N> const& b)
{
for(int i=0; i<N; ++i)
a.data[i]+=b.data[i];
return a;
}
template<typename T, int N>
const Vector<T,N> operator+(Vector<T,N> const& a, Vector<T,N> const& b)
{
Vector<T,N> tmp(a);
tmp+=b;
return tmp;
}
}
#endif // VECTORN_H