我有以下课程:
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'类型的全局运算符(或者没有可接受的转换))
有人能澄清这种情况吗? 感谢
答案 0 :(得分:3)
您可以通过以类似于以下的方式覆盖对MyInteger类的int
的强制转换来实现此目的:
class MyInteger {
...
operator int() const
{
return toStdInt(); /** Your class as an array index (int) */
}
...
}