I know that a return value is not enough to override a function, but is there a way to overload the subscript operator of a class, just to return the value (I can't changed to to return by reference-type of function)
it has to look like or at least work like:
What's the best approach to solve this problem?
1 2 3 4 5
struct A {int a; int b; double c;};
struct B {int a; int b; array<double,2> c;};
A operator [](unsignedint ) const; //it's just reading the element
B operator [](unsignedint ) const;
#include <iostream>
#include <string>
class A {
public:
A(std::string); //Constructor, which we need to have
charoperator[](constunsignedint index) const; //Here is the operator, but we can only read elements using it
int length() const;
private:
std::string my_string; //Some private variable, here it is a string
};
A::A(std::string s) {
my_string = s;
}
int A::length() const {
return my_string.length();
}
char A::operator[](constunsignedint index) const {
return my_string[index];
}
int main()
{
A some_object("This is my string");
std::cout << "The 4th character in some_object is: " << some_object[3] << std::endl;
//You can print out "my_string" character by character this way
std::cout << "Let's print it out character-by-character - I'll put a '_' in-between each character" << std::endl;
for (int i = 0; i < some_object.length(); i++)
{
std::cout << some_object[i] << "_";
}
}
The "const" there at the end of the function definition means that the function is promising to not modify anything inside the class inside of the function. In fact, any function that IT calls also needs to be const-qualified. Any attempt to modify the value using that operator will simply result in a compile-time error.
Thank you very much for your reply, I guess we are speak about something complete different (or at least I don't see how your answer actually relates to my question). My aim is to have one class, like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
struct A {int a; int b; double c;};
struct B {int a; int b; array<double,2> c;};
class Whatever
{
public:
A operator [](unsignedint ) const; //it's just reading the element
B operator [](unsignedint ) const;
}
A operator [](unsignedint Input){
//...
}
B operator [](unsignedint Input){
//...
}
You cannot two copes of the same operator that return different things and take the same arguments. Here you want to send an int into the [] operator, but you declare two different versions, each with a different return type - this cannot be done. The compiler wouldn't know which one to use since they both take the same arguments.
Putting your code into my compiler returns the following error:
Error: cannot overload functions distinguished by return type alone
There is no way to overload that operator twice by return type alone.