JDe*_*ein 4 c++ overloading const
假设String类中有两个重载的成员函数(const版本和非const版本):
char & String::operator[](int i) //Version 1
{
cout<<"char & String::operator[](int i) get invoked."<<std::endl;
return str[i];
}
const char & String::operator[](int i) const //Version 2
{
cout<<"const char & String::operator[](int i) const get invoked."<<std::endl;
return str[i];
}
Run Code Online (Sandbox Code Playgroud)
并且有一个测试代码片段
int main(){
String a;
cout<<a[0]<<endl; //Line 1
a[0]='A'; //Line 2
}
Run Code Online (Sandbox Code Playgroud)
编译器如何决定调用哪个函数?我发现在运行程序时总是调用版本1.谁能告诉我它为什么会这样?版本2如何被调用?
如果a是const,则会调用第二个重载.
int main(){
const String a;
cout<<a[0]<<endl; // would call const version
a[0]='A'; // will not compile anymore
}
Run Code Online (Sandbox Code Playgroud)
如果对象是const,则将调用const成员函数。如果对象是非常量对象,则调用非常量成员函数。
异常
如果它们只是 const 函数,则无论如何都会调用它。
#include <iostream>
using namespace std;
class Foo {
public:
void print() {
cout << "Foo non-const member function\n";
}
void print() const {
cout << "Foo const member function\n";
}
};
class Bar {
public:
void print() const {
cout << "Bar const member function\n";
}
};
int main() {
Foo foo_non_const;
const Foo foo_const;
Bar bar_non_const;
const Bar bar_const;
foo_non_const.print();
foo_const.print();
bar_non_const.print();
bar_const.print();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
$ ./废话
Foo non-const member function
Foo const member function
Bar const member function
Bar const member function
Run Code Online (Sandbox Code Playgroud)