【问题标题】:Given a pointer to a C++ object what are all the correct ways to call the operator[] function?给定一个指向 C++ 对象的指针,调用 operator[] 函数的所有正确方法是什么?
【发布时间】: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&lt;float&gt;&amp;,这应该接受p[d] 接受的订阅运算符。
  • 这真的很奇怪!在挣扎了四个小时并得到一致的编译器错误之后,现在它开始工作了。 8^P
  • @JEdwardEllis :也许您之前尝试过*pPtr[d]*(pPtr)[d]
  • 好吧,至少我现在有一个非常非常彻底的测试。

标签: c++ visual-studio visual-studio-2008 visual-c++


【解决方案1】:

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

【讨论】:

  • 特别是我在做 *(pPtr)[d].
【解决方案2】:

您已经列出了明智的选择。我不明白为什么指针取消引用不起作用。下面的编译就好了:

std::vector<int> v;
v.push_back(0);
v[0];

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

【讨论】:

  • 是的,我的现在也可以编译了。我无法解释为什么会出现编译器错误 C2677。
【解决方案3】:

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

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

所以,代码看起来更好:

f = pPtr->at(i); 

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2015-06-08
    • 2015-09-29
    • 2012-06-18
    • 2021-02-20
    • 1970-01-01
    相关资源
    最近更新 更多