Last active
November 19, 2019 23:19
-
-
Save Ajetski/98d4f65532f15471fdd5f180aea67e59 to your computer and use it in GitHub Desktop.
A gist for a small code snippet that needs improvement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class Test { | |
public: | |
Test(); | |
int& operator[](const int& index); | |
const int& operator[](const int& index) const; | |
private: | |
int arr[10] = {}; | |
}; | |
Test::Test() {} | |
//non-constant access | |
int& Test::operator[](const int& index){ | |
cout << "Inside Non-constant Method" << endl; | |
return arr[index]; | |
} | |
//constant access | |
const int& Test::operator[](const int& index) const{ | |
cout << "Inside Constant Method." << endl; | |
return arr[index]; | |
} | |
int main() { | |
Test t; | |
int i = t[2]; | |
const int j = t[2]; | |
t[3] = 3; | |
cout << i << endl; | |
cout << j << endl; | |
cout << t[3] << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment