- 常量函数 表示不允许修改类中的成员
int i,j //类中的成员
void Student::set(int j) const {
this->j = j; // 错误
cout<<i<<endl; // 正确
}
- 友元函数
在定义一个类的时候,可以把一些函数(包括全局函数和其他类的成员函数)声明为“友元”或一些类声明为友元,这样这些函数就成为该类的友元函数,在友元函数内部就可以访问该类对象的私有成员了。
friend void set(Student* stu); // 友元函数 在该函数内部可以访问Student类的私有变量
class Student {
friend void set(Student* stu);
friend class Friend; // 友元类 在该类中可以访问Student的私有变量
};
- 单例
class Runtime {
private:
static Runtime* instance;
Runtime();
public:
static Runtime* getInstance();
};
#include "Runtime.hpp"
Runtime::Runtime(){
}
Runtime* Runtime::instance = 0;
Runtime* Runtime::getInstance() {
if (!instance) {
instance = new Runtime();
}
return instance;
}