后面的 const 修饰行为:这个方法不能修改类中成员(mutable 成员除外)。
前面的 const 修饰返回值:如果返回复杂类型,其成员不能被修改。
struct A { int value; } class C { int prop1; mutable int prop2; void method1(int p1, int p2) const { // prop1 = p1; // ^ This will cause an ERROR. prop2 = p2; // OK because of `mutable`. } const A method2(int v) { A a; a.v = v; return a; } const int method3(int i) { // Here `const` is useless because `int` is a basic type. return i + 1; } } int main() { C c; A a = c.method2(1); // a.value = 114514; // ^ This will cause an ERROR. int i = c.method(3); i = 1919810; // OK }和直接使用这个函数有什么区别?安全上的区别。
showtooltip整理