As we know compiler determines the function by the overloaded function signature (like parameter types), but how does this one work:
v[i] = 1;
When compiler looks at these two overloaded functions:
const T& operator[](size_t i) const;
T& operator[](size_t i);
How does it determine which one to use? Does the compiler tries to use 1st one, and finds out it does not work, then it tries to use the second one?
If the object is non-const, the non-const version of the function is invoked (if it is available), else const version is invoked. Now see which is which:
const T& operator[](size_t i) const; //CONST MEMBER FUNCTION
T& operator[](size_t i); //NON-CONST MEMBER FUNCTION
An example,
void f(std::vector<int> const &v1, std::vector<int> & v2)
{
std::cout << v1[0] << std::endl; //invokes const version
std::cout << v2[0] << std::endl; //invokes non-const version
}
Now when you write:
v[i] = 1;
If I don't assume v
to be std::vector
, then it depends on the const-ness of the v
. If v
is const, then const-version will be invoked, else non-const version will be invoked (if it is available, else v
will convert into const object and then const function will be invoked).
The non- const
member function cannot be called on a const
object.
Hence, in order to be practically useful, the rules have to be that it's called on a non- const
object, and that conversely, the const
member function is called on a const
object.
And that's what the rules are.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.