开发者

Which overloaded version of operator will be called

开发者 https://www.devze.com 2022-12-17 21:24 出处:网络
Suppose i have declared subscript operators in a class char& operator[] (int index); const char operator[](int index) const;

Suppose i have declared subscript operators in a class

  1. char& operator[] (int index);
  2. const char operator[](int index) const;

In what condition the second ove开发者_C百科rload is called. Is it only called through a const object.

In the following scenarios which version of operator will be called.

const char res1 = nonConstObject[10]; 
nonConstObject[10];


The first one is called. Don't get confused by the return value; only the arguments are considered to select the method. In this case, the implicit this is non-const, so the non-const version is called.


Constant methods can only be called from constant instances. Since nonConstObject isn't defined as const then both calls will be to the non-const overloaded operator.

0

精彩评论

暂无评论...
验证码 换一张
取 消