You are not logged in.

Dear visitor, welcome to QtForum.org. If this is your first visit here, please read the Help. It explains in detail how this page works. To use all features of this page, you should consider registering. Please use the registration form, to register here or read more information about the registration process. If you are already registered, please login here.

1

Thursday, September 1st 2005, 8:35am

operator []

im having a hard time overloading subscipt operator,

this is my code snipet...

class MyClass {
public:
MyClass();

int & operator[](int x);
const int & operator(int x) const;

private:

// other codes
};

the code above works with this...

MyClass x;
x[1] = 1;

but a compile time error when im creating a pointer like this...

MyClass *x = new MyClass();

x[1] = 1;

error but if i use x->operator[](1) = 1; it compiles and i think it's a little bit weird, can anyone help me with this... thanks

This post has been edited 1 times, last edit by "happybear" (Sep 1st 2005, 8:36am)


AP.Sakkthivel

Professional

  • "AP.Sakkthivel" is male

Posts: 563

Location: India

Occupation: Application Development Using Qt

  • Send private message

2

Thursday, September 1st 2005, 9:44am

RE: operator []

Have you tried any other operators for this test?

can you check and update the same?
Regards
- $akthi

You never know, how soon it may be too lateā€¦

3

Thursday, September 1st 2005, 10:06am

i havent tried it yet, but same result happens when i try to use [] operator in QValueList;

QValueList<QString> *list = new QValueList<QString>();
list->append("test");

QMessageBox::information(0,"test",list[0]);

// but it will work with list->operator[](0);

and even with the std::vector, compile error is all i get..

can anyone explain this odd behavior?! thanks

jacek

Master

  • "jacek" is male

Posts: 2,729

Location: Warsaw, Poland

  • Send private message

4

Thursday, September 1st 2005, 12:29pm

Quoted

Originally posted by happybear
and even with the std::vector, compile error is all i get..
can anyone explain this odd behavior?! thanks

That's because operator[] was defined for an object, not a pointer to it.

Source code

1
2
3
4
5
6
7
8
9
10
SomeClass object;
SomeClass *ptr;
...
// these statements are OK (assuming that SomeClass::operator[] exists):
object[x];
ptr->[x];
(*ptr)[x];

// and this won't work:
ptr[x];
But if you create an array:

Source code

1
2
3
4
5
SomeClass *array = new SomeClass[100];
...
// this will work:
array[x];    // returns an object of SomeClass
array[x][y];