什么时候我需要实现运算符[]

When would I need to implement operator [] ?

本文关键字:运算符 实现 什么时候      更新时间:2023-10-16

给定以下模板函数:

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

我需要定义一个名为MyClass的类(仅声明,即只是.h文件),这将能够与模板函数一起工作。我定义了下面的声明:

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

我不明白的是为什么不需要为以下行定义操作符[]:

array[0]=obj1; array[1]=obj2; 

?什么时候需要定义运算符[]?谢谢你,罗恩

你为你的类型声明了一个数组:

T array[2];

但是你说的是为T实现operator[],这是完全不同的概念。

如果你需要

T t;
t[1] = blah

则需要实现operator[]

因为

T array[2];

不是一个T对象,它是一个T数组,所以

array[0];

正在索引一个数组,而不是你的对象之一,因此你不需要操作符[]。

假设您使用一对MyClass对象调用DoSomething,您已经声明arrayMyClass对象的普通数组。MyClass不需要[]操作符,因为array不是MyClass的实例;它只是一个数组。

当有意义或方便时,您将希望在自己的类中重载[]操作符。一个很好的例子是集合(如地图)。另一个例子是自定义字符串类,您可能希望通过regex对象进行索引,以便在字符串中查找模式的匹配项。

如果您的类是动态数组的实现,例如,您将希望访问(单个)对象,就好像是一个数组一样—您可以通过重载[]操作符来实现。