常量函數
函數後寫上const,表示不會也不允許修改類中的成員。
class Student {
int i;
public:
Student() {}
~Student() {}
// 常量函數
void setName(char* _name) const {
//錯誤 不能修改name 去掉const之後可以
name = _name;
}
private:
int j;
char *name;
protected:
int k;
};
靜態成員
和Java一樣,可以使用static來聲明類成員爲靜態的
當我們使用靜態成員屬性或者函數時候 需要使用 域運算符 ::
//Instance.h
#ifndef INSTANCE_H
#define INSTANCE_H
class Instance {
public:
static Instance* getInstance();
private:
static Instance *instance;
};
#endif
//Instance.cpp
#include "Instance.h"
Instance* Instance::instance = 0;
Instance* Instance::getInstance() {
//C++11以後,編譯器保證內部靜態變量的線程安全性
if (!instance) {
instance = new Instance;
}
return instance;
}