给定一个指向C++对象的指针,调用运算符[]函数的所有正确方法是什么

Given a pointer to a C++ object what are all the correct ways to call the operator[] function?

本文关键字:运算符 函数 调用 方法 是什么 指针 一个 对象 C++      更新时间:2023-10-16

我正在使用模板编写一个时变配置文件类,并希望通过数字索引或通过structtm表示的日期和时间对配置文件进行索引。通过数字索引进行索引可以很好地工作,但通过日期进行索引不适用于指向对象的指针。以下是一些示例代码,其中包含有效的方法和无效的方法。

#include "profile.h" // Class Profile<T> is declared and defined here.
float f;
int i;
struct tm d;
Profile<float> p;
Profile<float> *pPtr;
// Non-pointer syntax
f = p[i];                // this works.
f = p.operator[](i);     // this works, but its ugly.
f = p[d];                // this works.
f = p.operator[](d);     // this works, but its ugly.
// Pointer syntax
f = (*pPtr)[i];          // this works.
f = pPtr->operator[](i); // this works, but its ugly.
f = (*pPtr)[d];          // this isn't what I typed.  I did f = *(pPtr)[d];
f = pPtr->operator[](d); // this works, but its ugly.

此C++代码是在Visual Studio 2008中编写的。编译器错误消息是错误C2677二进制"[":找不到采用类型"tm"的全局运算符(或者没有可接受的转换)。

给定一个指向C++对象的指针,调用运算符[]函数的正确方法是什么?

这里显示的代码很好;可能在您之前的尝试中,您使用的是*(pPtr)[d]而不是(*pPtr)[d],这会导致错误,这是可以理解的,因为operator*的优先级低于operator[]

您已经列出了合理的选项。我不明白为什么指针取消引用不起作用。以下编译得很好:

std::vector<int> v;
v.push_back(0);
v[0];
std::vector<int>* vp = &v;
(*vp)[0];

在类似的情况下,我会在类中添加额外的方法,例如"at"。

templateType & Profile::at(int idx) 
{
    return operator[](idx);
}

所以,代码看起来更好:

f = pPtr->at(i); 

顺便说一句,在类方法(在我们的例子中是Profile)中使用at(idx)将比operator[](idx)更容易。