How can I define an operatpr [] for this class ?

#include <iostream>
using namespace std;

class Vec4 {
	float f1,f2,f3,f4;
public:
	Vec4(float ff1, float ff2, float ff3, float ff4): f1(ff1), f2(ff2), f3(ff3), f4(ff4) {}
	float operator [] (int index)
	{

	}
	Vec4 operator + (const Vec4& v)
	{
		return Vec4(f1 + v.f1, f2 + v.f2, f3 + v.f3, f4 + v.f4);
	}
	Vec4 operator - (const Vec4& v)
	{
		return Vec4(f1 - v.f1, f2 - v.f2, f3 - v.f3, f4 - v.f4);
	}
	Vec4 operator * (const Vec4& v)
	{
		return Vec4(f1 * v.f1, f2 * v.f2, f3 * v.f3, f4 * v.f4);
	}
	Vec4 operator / (const Vec4& v)
	{
		return Vec4(f1 / v.f1, f2 / v.f2, f3 / v.f3, f4 / v.f4);
	}
	Vec4& operator = (const Vec4& v)
	{
		f1 = v.f1;
		f2 = v.f2;
		f3 = v.f3;
		f4 = v.f4;
		return *this;
	}
	Vec4 operator += (const Vec4& v)
	{
		return Vec4(f1 += v.f1, f2 += v.f2, f3 += v.f3, f4 += v.f4);
	}
	Vec4 operator -= (const Vec4& v)
	{
		return Vec4(f1 -= v.f1, f2 -= v.f2, f3 -= v.f3, f4 -= v.f4);
	}
	Vec4 operator *= (const Vec4& v)
	{
		return Vec4(f1 *= v.f1, f2 *= v.f2, f3 *= v.f3, f4 *= v.f4);
	}
	Vec4 operator /= (const Vec4& v)
	{
		return Vec4(f1 /= v.f1, f2 /= v.f2, f3 /= v.f3, f4 /= v.f4);
	}
	friend ostream& operator << (ostream& os, const Vec4& v)
	{
		return os << v.f1 << " " << v.f2 << " " << v.f3 << " " << v.f4 << endl;
	}

};

int main()
{
	Vec4 v(1,2,3,4);
	Vec4 w(11,22,33,44);
	Vec4 z = v + w;
	cout << z;
}

How do you want people to access your 4D vector points? At first glance I'd think something like this would work for you--

float operator [] (int index)
{
	index = (index >= 0) ? ( (index <= 3) ? index : 3 ) : 0;
	switch(index){
		case 0:
			return f1;
		case 1:
			return f2;
		case 2:
			return f3;
		case 3:
			return f4;
	}
}

-- but do you want to be able to modify your 4D vector's internal values when calling the operator or not? Or, where do you want people to start in your operator for finding the points?

Instead of this float f1,f2,f3,f4; use an array like so float point4[4] . There are more benefits to use an array than 4 different variables.
Plus its easier to maintain.

This article has been dead for over six months. Start a new discussion instead.