Reputation: 11
i am trying to implement a "Integer" class with expect that it will work like a build-in type int
. But i am having a problem: i can't use this class in operator []
like int
See my code below:
#include <iostream>
using namespace std;
class Integer
{
private:
int Value;
public:
Integer(int x = 0)
{
Value = x;
}
void SetValue(int x)
{
Value = x;
}
int GetValue()
{
return Value;
}
Integer& operator [] (Integer X);
};
Integer& Integer::operator [] (Integer X)
{
// Code
}
int main()
{
Integer X[10];
Integer I(5);
int i = 5;
for(int i=0; i<10; ++i)
X[i].SetValue(i+1);
cout << X[i].GetValue() << endl; // It still work
cout << X[I].GetValue() << endl; // Doesn't work
return 0;
}
What is a way (exclude cast operator) to make operator []
understand my Integer type like it does with int
?
Upvotes: 1
Views: 123
Reputation: 68
Actually, you don't need to overload the [] operator. You just need to make sure that you can convert your Integer into an int with int int operator.
Something like this would work better.
operator int() const
{ return GetValue(); }
Then you should also be carefull with your prints.
X[i].GetValue()
is wrong since i = 10
in your exemple. This will result in an execution error.
X[I].GetValue()
is wrong in your exemple because de conversion between your class and an int is not possible without I.getValue()
. I am surprise this doesn't result in a compilation error but overloading the int operator will result this issue tho.
Upvotes: 0
Reputation: 234715
There's a bit of confusion here. The declaration of an array of type T
takes the form
T t[n];
where n
is a compile time evaluable constant expression for the array size.
This does not invoke any []
operator defined within T
, and neither does a subsequent access of an element via the expression t[i]
for an integral type i
.
If, in your case, you want X[I]
to be compilable then you need to provide an operator that allows I
to be treated as an array index (more formally the language requires a primitive integral type). A cast operator to int
is the obvious choice, with
operator int() const
{
return Value;
}
being the implementation.
Upvotes: 3
Reputation: 449
You'll need to add a type cast operator to your class. This allows your class to be converted to a compatible type. See here for more information: http://www.cplusplus.com/doc/tutorial/typecasting/
This function should do the trick for your class.
operator int() const { return GetValue(); }
Upvotes: 2
Reputation: 9682
You are thinking about this the wrong way around. You don't need to overload the [] operator on your own class, you actually need your class to be convertable to int, which can be done by overloading the cast operator.
class Integer
{
public:
operator int () const { return Value; }
};
Upvotes: 5