【发布时间】:2012-03-03 06:18:48
【问题描述】:
我正在使用模板编写一个随时间变化的配置文件类,并希望通过数字索引或由 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 中编写的。编译器错误消息是错误 C2677 二进制“[”:未找到采用“tm”类型的全局运算符(或没有可接受的转换)。
给定一个指向 C++ 对象的指针,调用 operator[] 函数的正确方法是什么?
【问题讨论】:
-
f = (*pPtr)[d]; // this doesn't work.我保证它确实有效;你看到了什么错误? -
(*pPtr)[d]不起作用是什么意思?由于*pPtr产生Profile<float>&,这应该接受p[d]接受的订阅运算符。 -
这真的很奇怪!在挣扎了四个小时并得到一致的编译器错误之后,现在它开始工作了。 8^P
-
@JEdwardEllis :也许您之前尝试过
*pPtr[d]或*(pPtr)[d]。 -
好吧,至少我现在有一个非常非常彻底的测试。
标签: c++ visual-studio visual-studio-2008 visual-c++