将关键字const写在函数头之后,函数体之前,说明该函数是一个const成员函数。此时const不是指定函数的返回值,而是修饰___指针。分值: 2
const 修饰函数体时,放到函数体的行尾处,表明在该函数体内,不能修改对象的数据成员,且不能调用非 const 成员函数。比如: void SetAge(int age) void SetAgeConst(int age) const 两者的区别在于:前者可以修改类的数据成员,而后者不可以。 #include<iostream>usingnamespacestd;classStudent{public:voidSetAge(int...
classTest{public:voidsetValue(constintvalue)const{ _value = value;// error C3490: '_value' cannot be modified because it is being accessed through a const object}private:int_value; }; 而const修饰函数体也只能用于类的成员函数,如果用于普通函数 voidtest()const{intk =0;// error C2270: 'te...
使用格式:fputs(ch,stdout); //stdout表示输出 2.const修饰符的使用 作用:const作用可以把修饰的变量变成只读的(常量) 1、修饰变量 const int a=23; int const a = 23; 2、修饰指针 const int *p; //指向可变 ,值不能变 int const *p; //同上 int * const p; //指向不可变,值可变 const int* c...
const int getValue(const char *key); // 返回值为不能被修改,函数体内不能修改参数的值 后来碰到一些写法如 const int getValue(const char *key) const; 对于最后一个const不甚理解,查资料后才明白这个用于类的成员函数修饰函数体,表示该函数体内类的成员变量的值不能被改变 class Test { public: void ...
_value = value;// error C3490: '_value' cannot be modified because it is being accessed through a const object}private:int_value; }; 而const修饰函数体也只能用于类的成员函数,如果用于普通函数 voidtest()const{intk =0;// error C2270: 'test' : modifiers not allowed on nonmember functions...