给定一个指向C++对象的指针,调用运算符[]函数的所有正确方法是什么
Given a pointer to a C++ object what are all the correct ways to call the operator[] function?
我正在使用模板编写一个时变配置文件类,并希望通过数字索引或通过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)
更容易。
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 C++ 中调用类中的运算符函数
- 错误 C2676:std::set::const_iterator 没有运算符 + 函数?
- 为什么 ADL 的运算符函数行为与其他函数不同?
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 第二个常量在运算符函数中做什么?
- 重载赋值运算符函数和复制构造函数中的错误
- 内置类型的运算符函数
- 如何调用运算符函数添加两个对象?
- Const 仍然允许在运算符函数 c++ 下进行更改
- 在呼叫运算符函数const中调用运算符时错误
- 是否有一种方法可以在超载运算符函数中接触默认运算符函数
- 重载时获取堆栈溢出 >> 运算符函数是为类调用的。我需要进行哪些更改?
- 运算符 [] 函数的实现是如何工作的
- C++:使用父类运算符函数更新子类对象的继承变量
- 创建一个接受 2 个输入参数的文本运算符函数
- 为什么找不到重载运算符函数?
- 为什么auto_ptr中有模板复制构造函数和覆盖运算符函数
- 为什么某些C++标准库“运算符<<”函数将其流宽度重置为 0
- C++SFINAE运算符/函数结果类型检查