问题及代码:
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student() {}
Student( const string& nm, int sc = 0 ): name(nm), score(sc) {} //只能通过构造函数的参数初始化表对常数据成员进行初始化
//(1)下面的const干神马?_____________
void set_student( const string& nm, int sc = 0 ) //nm设为常数据成员
{
name = nm;
score = sc;
}
//(2)下面的const分别干神马?___________
const string& get_name() const //常成员函数调用常数据成员
{
return name;
}
int get_score() const //常成员函数
{
return score;
}
private:
string name;
int score;
};
//(3)下面的const干神马?_____________
void output_student(const Student& student ) //常对象的引用
{
cout << student.get_name() << "\t";
cout << student.get_score() << endl;
}
int main()
{
Student stu( "Wang", 85 );
output_student( stu );
return 0;
}
运行结果:
知识点总结:
常数据成员 const int hour 只能通过构造函数的参数初始化表对常数据成员进行初始化。
常成员函数 类名 函数名 (参数表)const; 声明函数和定义函数的时候都要有const 关键字,调用时不加const
const对象 不能被非const的普通成员函数引用
而在常对象中声明可变的成员函数时 在前面加 mutable
mutable int hour