I’m new here so I hope I will write understandable question.
My problem is, how to access a static array in class by using overloaded operator ().
Main.cpp:
class SomeClass
{
public:
static const int a[2][2];
const int& operator() (int x, int y) const;
};
Just under it, I define the array a:
const int SomeClass::a[2][2] = {{ 1, 2 }, { 3, 4 }};
Here is the overloaded operator:
const int& SomeClass::operator() (int x, int y) const
{
return a[x][y];
}
In main(), I want to access ‘a’ 2D array just by using SomeClass(1, 1) which shloudl return 4. But when I try to compile main like this:
int main(void)
{
cout << SomeClass(1, 1) << endl;
return 0;
}
I get this error:
PretizeniOperatoru.cpp: In function ‘int main()’:
PretizeniOperatoru.cpp:22:22: error: no matching function for call to ‘Tabulka::Tabulka(int, int)’
PretizeniOperatoru.cpp:22:22: note: candidates are:
PretizeniOperatoru.cpp:5:7: note: SomeClass::SomeClass()
PretizeniOperatoru.cpp:5:7: note: candidate expects 0 arguments, 2 provided
PretizeniOperatoru.cpp:5:7: note: SomeClass::SomeClass(const SomeClass&)
PretizeniOperatoru.cpp:5:7: note: candidate expects 1 argument, 2 provided
I realised I don’t know, where is the problem. It seems that there is called a constructor of the class. It seems that I’m constructing the class instead of accessing the array.
What does it mean? Is there any way to do the array like this or it would be better to break rules of encapsulation and define it as global? Does it mean, that overloaded operators cannot be used to access static arrays?
When I do it this way, it compiles OK:
int main(void)
{
SomeClass class;
cout << class(1, 1) << endl;
return 0;
}
Thanks for response and hope my problem makes sense. I didn’t use [] operator for accessing, because it is more hard to implement than ( ).
You need to instantiate an object of your class to access its members. Try using
instead, instantiating a temporary and using it’s operator().