重载解析,为什么优先匹配非const版本?该如何处理
重载解析,为什么优先匹配非const版本?
下面这个小程序,运行结果是: operator s1()
如果我去掉非const的版本,那么调用的结果就是:operator s1() const
这是为什么? C++标准有没有规定const和非const的那个在重载解析的过程中优先匹配?
------解决方案--------------------
++
参数表括号后面的const 修饰的要this指向的对象,也可以说是调用对象。如果对象本身带有const修饰,就会优先重载const版本了,而你这里s()构造的临时对象并没有const修饰,所以优先选择非const版本,请看下面代码:
下面这个小程序,运行结果是: operator s1()
- C/C++ code
#include<iostream> using namespace std; struct s; struct s1{ const s* m_s; }; struct s{ operator s1()const{ cout << "operator s1() const" << endl; return s1(); } operator s1(){ cout << "operator s1()" << endl; return s1(); } }; void test(s1 obj){} int main(void){ test(s()); return 0; }
如果我去掉非const的版本,那么调用的结果就是:operator s1() const
这是为什么? C++标准有没有规定const和非const的那个在重载解析的过程中优先匹配?
------解决方案--------------------
++
参数表括号后面的const 修饰的要this指向的对象,也可以说是调用对象。如果对象本身带有const修饰,就会优先重载const版本了,而你这里s()构造的临时对象并没有const修饰,所以优先选择非const版本,请看下面代码:
- C/C++ code
#include<iostream> using namespace std; struct s; struct s1{ const s* m_s; }; struct s{ operator s1()const{ cout << "operator s1() const" << endl; return s1(); } operator s1(){ cout << "operator s1()" << endl; return s1(); } }; void test(s1 obj){} int main(void){ const s sa;//这个const影响重载选择的版本 test(sa); return 0; }