我正在使用模板编写一个时间变化的配置文件类,并且希望通过数值索引或struct tm表示的日期和时间进行索引。数值索引可以正常工作,但是使用指向对象的日期索引无法正常工作。以下是一些包含可行和不可行方法的样例代码。
#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中编写的。编译器错误提示为 error C2677 binary '[' : no global operator found which takes type 'tm' (or there is no acceptable conversion).
给定一个C++对象的指针,调用 operator[] 函数的所有正确方式有哪些?
(*pPtr)[d]
不能用吗? 因为*pPtr
返回的是一个Profile<float>&
,它应该接受一个subscribe操作符,而这个操作符对于p[d]
是可接受的。 - Dietmar Kühl*pPtr[d]
或者*(pPtr)[d]
。 - ildjarnProfile<float>::operator[](const ::tm&)
? - André Caron