什么时候我需要实现运算符[]
When would I need to implement operator [] ?
给定以下模板函数:
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
,您已经声明array
为MyClass
对象的普通数组。MyClass
不需要[]
操作符,因为array
不是MyClass
的实例;它只是一个数组。
当有意义或方便时,您将希望在自己的类中重载[]
操作符。一个很好的例子是集合(如地图)。另一个例子是自定义字符串类,您可能希望通过regex对象进行索引,以便在字符串中查找模式的匹配项。
如果您的类是动态数组的实现,例如,您将希望访问(单个)对象,就好像是一个数组一样—您可以通过重载[]操作符来实现。
相关文章:
- 如何正确实现和访问运算符的各种自定义枚举器
- 三向比较运算符成员与非成员实现
- C++矩阵类运算符使用 std::common_type_t 和复数的实现
- 如何为我的类实现/重载二进制运算符
- 默认赋值运算符如何在实际 STL 中实现
- 使用'+='运算符统一实现 C++ '+'运算符
- 运算符+ 的规范实现涉及额外的移动构造函数
- 如何在层次结构中实现运算符使用?
- 如何在C++中实现切片运算符[]?
- C++ 20 中的运算符 == 和 <=> 应该作为成员还是自由函数实现?
- 将赋值运算符实现为"destroy + construct"是否合法?
- 为模板类中的>>运算符和<<运算符实现重载
- 使用括号运算符实现矩阵类的安全方法
- 分配运算符实现的说明
- 为什么 std::sort 不使用我的运算符<实现
- 复制构造函数和赋值运算符实现选项 -
- 如何在最大限度地提高大小有效性的同时,将3态的位运算符实现为任何大小的内存
- 将比较运算符"运算符<"实现为成员函数或外部函数
- 如何使用+=运算符实现标量和向量相加
- 为什么运算符>由 C++ STL 库中的运算符* 实现?