常对象
const 类型(或引用类型)变量(对象)
const修饰的变量或引用的对象,即为常对象。不能对其修改
常对象只能调用常函数,不能调用普通函数。因为普通函数拥有修改类中属性的权限。
非const修饰的普通对象,不仅有读的权限,也有写的权限,所以普通对象可以调用常函数。
常函数
class 类名
{
public:
返回值 函数名(形参列表)const
{
//常函数的函数体,函数体中只可以读取类中的属性,不可修饰类中的属性。
}
};
一个类中的const修饰函数体的成员函数。就叫常函数。
常函数的函数体,只能获取(读数据),不可以写数据,不可修饰类中属性。
常函数一般用在获取数据时,保证数据安全。
例:
#include <iostream>
using namespace std;
class Stu
{
public:
string name;
int age;
public:
Stu(string name, int age)
{
this->name = name;
this->age = age;
}
//2.返回本对象。
Stu& setName(string name)
{
this->name = name;
return *this;
}
string getName()const
{
return this->name;
}
int getAge()const
{
return this->age;
}
};
//常对象与常函数验证示例:
void showInfo(const Stu& stu)
{
cout << "姓名:" << stu.getName() << ",年龄:" << stu.getAge() << endl;
}
int main()
{
Stu stu("zhangsan",18);
showInfo(stu);
return 0;
}