given the following template function :
template <class T>
void DoSomething(T &obj1, T &obj2)
{
if(obj1 > obj2)
cout<<"obj1 bigger: "<<obj1;
else if(obj1 == obj2)
开发者_如何学编程 cout<<"equal";
else cout<<"obj2 bigger: "<<obj2;
T tmp(3);
T array[2];
array[0]=obj1;
array[1]=obj2;
}
I need to define a class called MyClass (declarations only , i.e. just the .h file) , that would be able to work with that template function . I defined the next declarations :
class MyClass
{
public:
MyClass(); // default ctor
MyClass(int x); // for ctor with one argument
bool operator ==(const MyClass& myclass) const;
bool operator >(const MyClass& myclass) const;
friend ostream& operator<<(ostream &out,const MyClass& myclass); // output operator
};
What I don't understand is why there is no need to define operator [] for the lines:
array[0]=obj1; array[1]=obj2;
? When would I need to define operator []? thanks ,Ron
You declared an array for your type:
T array[2];
But your are talking about implementing operator[] for T
, which is totally different concept.
If you need
T t;
t[1] = blah
Then you need to implement operator[]
Because
T array[2];
Isn't a T object, its an array of T. So
array[0];
Is indexing an array, not one of your objects, therefore you don't need an operator[].
Assuming you call DoSomething
with a couple of MyClass
objects, you have declared array
to be a normal array of MyClass
objects. You did not need a []
operator for MyClass
because array
is not an instance of MyClass
; it is just an array.
You will want to overload the []
operator in your own classes when it makes sense to, or is convenient. A good example is a collection (such as a map). Another example is a custom string class, where you might want to index by a regex object to find matches for your pattern inside your string.
If your class was an implementation of a dynamic array, for example, you would want to access the (single) object as though it was an array - you this by overloading the [] operator.
精彩评论