Calling a const function rather than its non-const version

前端 未结 4 1437
深忆病人
深忆病人 2020-11-28 13:38

I tried to wrap something similar to Qt\'s shared data pointers for my purposes, and upon testing I found out that when the const function should be called, its non-const ve

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 14:08

    If you have two overloads that differ only in their const-ness, then the compiler resolves the call based on whether *this is const or not. In your example code, test is not const, so the non-const overload is called.

    If you did this:

    testType test;
    const testType &test2 = test;
    test2->x();
    

    you should see that the other overload gets called, because test2 is const.

提交回复
热议问题