How to access the C ++ indexing operator from the class in which it is located?

Where ClassA has an operator as such that returns ClassB:

class ClassA { public: ClassA(); ClassB &operator[](int index); } 

If I want to access the specified operator from the ClassA constructor, like this:

 ClassA::ClassA() { // How do I access the [] operator? } 

At the moment, when I work, I just use the GetAtIndex (int index) method, which calls the [] operator, as well as the constructor.

It would be nice if I could access it in the same way that C # works:

 // Note: This is C# class ClassA { ClassB this[int index] { get { /* ... */ } set { /* ... */ } } void ClassA() { this[0] = new ClassB(); } } 

Note: I am using g ++

+4
source share
5 answers

Try to execute

 (*this)[0] = ... 
+8
source

You can use:

 this->operator[](0) = ... 

or

 (*this)[0] = ... 

But the syntax is a bit uncomfortable. Usually I make another method called get and use it, for example:

 ClassB& get(size_t index) { return this->operator[](0); // or something more direct } 

Then, when you want to use it, you can simply say:

 this->get(0) = ... 
+10
source
  ClassA::ClassA() { this->operator[]( someindex ) = whatever; } 

But make sure that all the members that the operator may depend on are fully constructed before using it.

0
source

Here's another way, not sure if it is useful ...

 ClassA::ClassA() { ClassA &_this = *this; _this[0] = someValue; _this[1] = someValue; _this[2] = someValue; _this[3] = someValue; _this[4] = someValue; } 
0
source

Two different ways:

 ( *this ) [ index ] or this -> operator [ ] ( index ) 
0
source

All Articles