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
- oneWhat 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
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
- 2I 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; }
|