const 成员函数

目录:

  1. const成员函数
  2. const对象
  3. 总结

在类中,如果不希望某些数据被修改,可以用const关键字加以限定,const可以用来修饰成员变量,成员函数以及对象

const成员函数

const成员函数可以使用类中所有的成员变量,但是不能修改它们的值,const成员函数也称为常成员函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Student{
public:
Student() = default;
Student(char *name, int age, float score);
void show();
//声明常成员函数
char *getname() const;
int getage() const;
float getscore() const;
private:
char *m_name;
int m_age;
float m_score;
};
Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }//初始化列表
void Student::show(){
cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
}
//定义常成员函数
char * Student::getname() const{
return m_name;
}
int Student::getage() const{
return m_age;
}
float Student::getscore() const{
return m_score;
}

getname(),getage(),getscore()三个函数的功能仅仅是为了获取成员变量的值,没有修改成员变量的企图,故添加const限制可以使语义更加明显,也让程序更富有健壮性,更灵活。
需要注意的是,在常成员函数的声明和定义的参数列表后均要加上const修饰:
int getage() const
int Student::getage() const{...}

如果两个函数的名称和参数都相同,一个有const限定,一个没有,算重载,使用时具体调用哪一个函数取决于对象的类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CTest{
private :
int n;
public:
CTest(){n = 1;}
int GetValue() const {return n;}
int GetValue() {return 2*n;}
};
int main()
{
const CTest objTest1;
CTest objTest2;
cout<<objTest1.GetValue()<<","<<objTest2.GetValue(); //1,2
return ();
}

const对象

const也可以用来修饰对象,称为常对象,一旦对象被定义为const对象,则该对象只能调用const成员函数,因为const对象即意味着其成员变量不可以被修改,如果调用非const成员函数,则有可能会修改其成员变量,编译会报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Sample
{
public:
Sample() = default;
Sample(int n):value(n){ };
void GetValue() const;
void func() {};
private:
int value;
};
void Sample::GetValue() const
{
value = 0; //err
func(); //err
}
int main()
{
const Sample o;
o.value = 100; //错错错,1.类的private成员不允许直接修改访问
//2.对象为const类型,不能修改数据
o.func(); //err,常量对象上面不能执行非常量成员函数
o.GetValue(); //ok,常量对象上可以执行常量成员函数
return 0 ;
}

总结

  1. 如果不需要修改类中的成员,尽量使用const成员函数
  2. 普通的对象可以调用类中所有的成员,const对象只能调用const成员