gpt4 book ai didi

c++ - 对象作为数组索引

转载 作者:太空狗 更新时间:2023-10-29 21:23:13 25 4
gpt4 key购买 nike

我有以下类(class):

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()));
}

可以解决我的问题,因为正如这篇文章所报道的那样 ( Type of array index in C++ )“表达式 E1[E2] 与 *((E1)+(E2)) 相同(根据定义)”,但我得到了 C2677 错误(“[”运算符:未找到采用“MyInteger”类型的全局运算符(或没有可接受的转换))

有人可以向我解释一下这种情况吗?谢谢

最佳答案

您可以通过以类似于以下方式重写对 MyInteger 类的 int 的强制转换来做到这一点:

class MyInteger {
...

operator int() const
{
return toStdInt(); /** Your class as an array index (int) */
}

...
}

关于c++ - 对象作为数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18764813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com