int length() const;
此只能使用于成员函数,意思为此函数里不能对函数所在类中的所有成员变量进行修改,他相当于对默认传递到length函数里的this指针加上const的限定,const OneClass * this;
const int length();
可以用于成员函数和非成员函数,表示函数返回值是常量。对于int型的返回值,本身就是使用的值传递返回,所以const修饰int返回值是无意义的,在返回指针的情况下const修饰返回值才有意义
class foo
{
public:
foo()
{
n = 10;
}
const foo * function1()
{
return this;
}
foo * const function2()
{
return this;
}
int n;
};
/*function1函数返回的指针是指向常量的指针,就不能赋值给非常指针,
如:
foo f;
foo * pf1 = f.function1();
这段代码就会报错
而function2函数的const修饰没有任何作用,因为函数返回按照值传递
*/