NDK13_C++基礎:常量函數、靜態成員

NDK開發彙總

常量函數

函數後寫上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;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章