migue
asked on
subscript op and function call op
I cannot get this to compile: problems with the operators
class FOO {
public:
int operator () (void) {
return(1);
}
int operator [] (unsigned index) {
return(array[index]);
}
private:
int array[10];
}
FOO *foo;
int main(void) {
foo = new FOO();
int result = (some boolean expresion) ? foo[3] : 0; // compiler does not foo[3] in this line
int result2 = (some boolean expression) ? foo(3) : 0; // compiler does not like foo(3) either
delete foo;
return 0;
}
Thanks.
I tried this in both watcom c/c++ 10.0b and borland 5.02 c++
class FOO {
public:
int operator () (void) {
return(1);
}
int operator [] (unsigned index) {
return(array[index]);
}
private:
int array[10];
}
FOO *foo;
int main(void) {
foo = new FOO();
int result = (some boolean expresion) ? foo[3] : 0; // compiler does not foo[3] in this line
int result2 = (some boolean expression) ? foo(3) : 0; // compiler does not like foo(3) either
delete foo;
return 0;
}
Thanks.
I tried this in both watcom c/c++ 10.0b and borland 5.02 c++
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
FOO Foo;
Then
int i = Foo[3];
would work.
You can fix this by declaring Foo as a FOO as shown above or by making it a reference, like
FOO &Foo = new FOO;
(Kind of unusual, but works.) Or you can continue to keep Foo a pointer to FOO and change your syntax with the [] operator, like
FOO *Foo;
int i = (*Foo)[3];
Obviously, your attempt to use parenthesis (that is, Foo(3)) has the same problem as well as the fact that the parenthesis operator does not accept an integer parameter. Thus you could change Foo to an object or a reference to an object and then you could do Foo(). Or you can keep it a pointer and do (*Foo)().