要求接收方调用返回值是const修饰,这不是白白增加了约束么?
const char * GetString(void);
char *str = GetString();//报错
非const不能调用const
class A{
public:
void func1(void) const {
cout << "常函数" << endl;
// func2(); //错误 因为func1是const类型的
}
void func2(void) {
cout << "非常函数" << endl;
m_i++;
func1();
}
private:
int m_i;
};
同一个名字的函数可以有两个,通过有无const来区分
class A{
public:
void func(int a = 0) const{
cout << "常函数" << endl;
}
void func(int a = 0){
cout << "非常函数" << endl;
}
private:
int m_a;
};
int main() {
A a;
a.func();
const A a1 = a; //const 匹配后面一个函数
a1.func();
}
无法理解这些古怪的约束用处何在。。。