In a project of mine, I'm writing a wrapper for std::vector
. I'm doing this because I am using homogeneous coordinates and for some operations it's just easier to temporarily 'forget' the fourth coordinate.
Now I stumbled upon a problem. I have loads of assignments like the following:
Vector v;
v(0) = 5;
v(1) = 6;
and so on. I also want to do the following:
double x;
x = v(0);
For that last thing, I can overload the () operator, but how would implement the f开发者_如何学编程irst thing? (the zero and one being an index).
Just return reference.
class Vector
{
int data[4];
int & operator() (int index) { return data[index]; }
};
Return a non-const reference to the element to be modified.
Two things-
You should probably be overloading
operator[]
to do this rather thanoperator()
, since it's the more natural operator here.operator()
is used to create function objects, whileoperator[]
is the operator meaning "pick out the element at this position."You can support assignment to the result of
operator[]
/operator()
by having the function return a reference to the value that should be written to. As a simple example, here's some code that represents a class wrapping a raw array:
(code here:)
class Array {
public:
int& operator[] (unsigned index);
int operator[] (unsigned index) const;
private:
int array[137];
};
int& Array::operator[] (unsigned index) {
return array[index];
}
int Array::operator[] (unsigned index) const {
return array[index];
}
The second of these functions is a const
overload so you can have const Array
read but not write values.
In the standard libraries, such things are implemented by having operator()
(well, actually usually operator[]
) return type double &
. By returning a reference to a double, you can assign to or from it.
However, are you sure you want to wrap this around std::vector
? This class is not a vector in the mathematical sense; it's much like a Java ArrayList
, and so not at all efficient for small structures. Usually when I'm writing my own vector classes I'm planning on having lots of them around, so I implement a class from scratch on top of a static array.
精彩评论