c++ - 我什么时候需要实现 operator [] ?

标签 c++ class templates

给定以下模板函数:

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[]

关于c++ - 我什么时候需要实现 operator [] ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7240304/

相关文章:

c++ - 每次获取不同的地址

c++ - 函数调用作为数组元素

c++ - 当我编译我的程序时,这个内存映射意味着什么?

c++ - 一般来说,当它们共享同一个父类时,是否有办法从另一个子类访问子类?

java - 如何分割java类文件(.java)

c++ - 提升icl interval_map interval_set模板

c++ - 如何编写将二进制数转换为十进制数的递归函数?

C++:显式与隐式默认初始化

c++ - 将范围传递给 C++ 算法时如何处理 iterator/const_iterator 不匹配?

c++ - 为什么 Curiously Recurring Template Pattern (CRTP) 有效