#include <iostream>
using namespace std;
struct A {
int count() {
cout << "non const" << endl;
return 1;
}
int count() const {// 调用对象不能被修改
cout << "const" << endl;
return 1;
}
int count(int& s) {
cout << "non const(ref arg)" << endl;
return 1;
}
int count(const int& s) {// 参数不能被修改
cout << "const(ref arg)" << endl;
return 1;
}
};
int main () {
A a;
a.count();// 调用对象不是const
const A ca;
ca.count();// 调用对象是const
a.count(4);// 参数是const
int x = 4;
a.count(x);// 参数不是const
return 0;
}
non const
const
const(ref arg)
non const(ref arg)
从上面的输出结果我们也可以看到:
1. const修饰的对象调用的是使用const修饰的方法,非const对象调用的是非const的方法。
2. 不只是参数类型和个数不同会产生重载,const修饰的参数也会有重载。但是只有当const修饰的是指针或者引用类型时才可以,普通的int和const int会编译失败!
本文详细探讨了C++中const对象如何选择调用相应的方法,指出const对象会调用const修饰的方法,而非const对象则调用非const方法。此外,还阐述了const参数在函数重载中的作用,强调只有const修饰的指针或引用参数才能产生重载,并通过实例展示了其工作原理。
800

被折叠的 条评论
为什么被折叠?



