Show some sensible example of overloading the operator [] and ()

  • Something was on: [habrahabr.ru] [1] [1]: habrahabr.ru/blogs/cpp/132014 - nikita_sergeevich
  • there is not enough information about [], () - nullptr
  • one
    What do not you understand? And what does "sensible" mean? See the classics: Straustrup, Laforet, Josattis. There are a lot of good examples of overloading these operators. - skegg

2 answers 2

Arithmetic progression. The [] operator returns the nth member, and () the sum of the first n members of an arithmetic progression:

class ArithProgression { public: ArithProgression(int a1, int d) {this->a1=a1, this->d=d;} int operator[](int n) {return a1+d*(n-1);} int operator()(int n) {return (2*a1+d*(n-1))*n/2;} private: int a1, d; }; int main() { ArithProgression ap1(1, 2); cout << ap1[6] << ' ' << ap1(6) << endl; ArithProgression ap2(100, -3); cout << ap2[14] << ' ' << ap2(14) << endl; return 0; } 

Answer the question from the comments:

Through the operator [] this is done like this:

 class Vector { public: ...Π”Ρ€ΡƒΠ³ΠΎΠΉ ΠΊΠΎΠ΄... float& operator[](int index) {return ((float*)this)[index];} float x, y, z, w; }; class Matrix { public: ...Π”Ρ€ΡƒΠ³ΠΎΠΉ ΠΊΠΎΠ΄... Vector& operator[](int index) {return data[index];} Vector data[4]; }; 

For matrices and vectors, the operator [] can not be overloaded at all. If you store the matrix as an array of vectors, you can override operator Vector* . Thus, the matrix will implicitly be a pointer to a vector, and the pointer itself supports []. For a vector, you can also define an operator float* . Here is the implementation of this method:

 class Vector { public: ...Π”Ρ€ΡƒΠ³ΠΎΠΉ ΠΊΠΎΠ΄... operator float*() {return (float*)this;} float x, y, z, w; }; class Matrix { public: ...Π”Ρ€ΡƒΠ³ΠΎΠΉ ΠΊΠΎΠ΄... operator Vector*() {return data;} Vector data[4]; }; Π˜ΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ ΠΎΠ±Π° Π²Π°Ρ€ΠΈΠ°Π½Ρ‚Π° ΠΌΠΎΠΆΠ½ΠΎ Ρ‚Π°ΠΊ: Matrix matrix; ...Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ ΠΌΠ°Ρ‚Ρ€ΠΈΡ†Ρ‹... cout << matrix[1][2] << ' ' << matrix[1].z << endl; if(matrix[1][2]!=matrix[1].z) cout << "Error!" << endl; //Π’Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ΡŒ Π½Π΅ Π΄ΠΎΠ»ΠΆΠ½ΠΎ, Ρ‚Π°ΠΊ ΠΊΠ°ΠΊ индСкс 2 соотвСтствуСт z-ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Π΅. 
  • and how to reboot, for example, [] []? - nullptr
  • 2
    I would make an inner class for this, which would return the operator [] of the main class and in turn would be overloaded with []. - skegg
  • well, for example, matrix [1] [2] = 10; How to do it? - nullptr 2:32 pm
  • > well, for example, matrix [1] [2] = 10; - how to do it? Added your answer. - gammaker

And you can be stupid? You are welcome:

 #include <iostream> #include <strings.h> using namespace std; class dumbexample { private: int *arr; int n; public: dumbexample(int n1) { n = n1; arr = new int[n]; bzero(arr, n*sizeof(int)); } ~dumbexample() {} int& operator[] (int i) {return arr[i];} int operator() (int i) {return arr[i]*i;} }; int main() { dumbexample a(6); a[2] = 5; cout << a[2] << endl; cout << a(2) << endl; }