对象作为数组索引
Object as array index
我有以下类:
class MyInteger
{
private:
__int64 numero;
static __int64 int64Pow(__int64, __int64);
public:
// It doesn't matter how these methods are implemented
friend class MyInteger;
MyInteger(void);
MyInteger(const MyInteger&);
MyInteger(const __int64&);
~MyInteger(void);
static MyInteger const minValue;
static MyInteger const maxValue;
MyInteger& operator = (const MyInteger&);
MyInteger operator + (const MyInteger&) const;
MyInteger operator - (const MyInteger&) const;
MyInteger operator * (const MyInteger&) const;
MyInteger operator / (const MyInteger&) const;
MyInteger& operator += (const MyInteger&);
MyInteger& operator -= (const MyInteger&);
MyInteger& operator *= (const MyInteger&);
MyInteger& operator /= (const MyInteger&);
MyInteger operator % (const MyInteger&) const;
MyInteger& operator %= (const MyInteger&);
MyInteger& operator ++ ();
MyInteger operator ++ (int);
MyInteger& operator -- ();
MyInteger operator -- (int);
bool operator == (const MyInteger&) const;
bool operator != (const MyInteger&) const;
bool operator > (const MyInteger&) const;
bool operator < (const MyInteger&) const;
bool operator >= (const MyInteger&) const;
bool operator <= (const MyInteger&) const;
int toStdInt() const
{
return (int)numero;
}
float toStdFloat() const;
double toStdDouble() const;
char toStdChar() const;
short toStdShortInt() const;
long toStdLong() const;
long long toStdLongLong() const;
unsigned int toStdUInt() const;
__int64 toStdInt64() const;
unsigned __int64 toStdUInt64() const;
unsigned long long int toStdULongLong() const;
long double toStdULongDouble() const;
template<class Type>
Type& operator[](Type* sz)
{
return sz[toStdULongLong()];
}
};
template<class Type>
Type* operator+(const Type* o1, const MyInteger& o2)
{
return ((o1) + (o2.toStdInt()));
}
我想使用这个类来访问这样的数组元素:
MyInteger myInt(1);
int* intPtr = (int*)malloc(sizeof(int) * N);
intPtr[myInt] = 1;
我以为函数
template<class Type>
Type* operator+(const Type* o1, const MyInteger& o2)
{
return ((o1) + (o2.toStdInt()));
}
可以解决我的问题,因为正如这篇文章报告的那样(C++ 中的数组索引类型)"表达式 E1[E2] 与 *((E1)+(E2))相同(根据定义)",但我收到 C2677 错误("["运算符:没有找到采用类型"MyInteger"的全局运算符(或者没有可接受的转换))
有人可以澄清我这种情况吗?谢谢
您可以通过以
类似于以下内容的方式重写 MyInteger 类int
的强制转换来执行此操作:
class MyInteger {
...
operator int() const
{
return toStdInt(); /** Your class as an array index (int) */
}
...
}
相关文章:
- 特征获取索引数组,其中向量中的值为真(不需要循环)
- 是否可以使用字符串或字符索引数组
- 为什么在使用字符索引数组时会出现这种不同的行为
- 在具有重复索引的索引数组处更改 ArrayFire 数组
- 使用索引数组订购 ArrayFire Array 的最佳方式
- C++ 中结构的动态索引数组
- 1索引数组上的qsort()正在扰乱索引
- C++ 索引数组打印和删除字符串名称 数组打印
- 字符串下标超出范围.我不知道如何使用字符索引数组,所以我使用了(无符号整数),但它不起作用
- openGL drawElements - 一个额外的三角形,使用索引数组
- 具有索引数组的地形(高度贴图)LOD
- 通过创建索引数组进行 C++ 排序
- OpenGL:两个顶点数组 + 两个索引数组
- 将索引数组排序为主数组
- 自动循环跳过某些索引数组
- 为静态强制转换的索引数组生成数组
- 重载枚举索引数组的std::get
- 使用c++中的第二个索引数组对数组进行排序
- 给定的零索引数组 &该数组的均衡索引
- CUDA:重新索引数组