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;
}




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