静态成员
静态成员用static 进行声明,需要注意的是,静态成员并不属于某一个object,而是属于这个类本身。所以,不管你用这个类创建了多少个实例,系统永远只为静态成员分配一份空间,所有的类均共享这一份数据。当时用的时候,静态成员需初始化,否则会显示链接错误。初始化的时候,可以赋予初值,也可以不赋初值。
静态成员函数
和静态成员类似,静态成员函数,也使用static进行声明。静态成员函数也不属于任何对象,只属于类本身。而对于C++来说,当一个实例调用函数时,C++会传一个this给这个实例,用this->memberfunction来进行调用,但是因为静态成员函数没有this指针,所以这个决定了静态成员只能访问静态成员变量。这也是静态成员的作用,用来修改类中的静态成员变量。
了解了基本概念之后看下面这道题,
Singleton is a most widely used design pattern. If a class has and only has one instance at every moment, we call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it in singleton.
You job is to implement a getInstance
method for given class, return the same instance of this class every time you call this method.
class Solution {
private:
static Solution *cur; //static member
public:
/**
* @return: The same instance of this class every time
*/
static Solution* getInstance() {
// write your code here
if (cur == NULL) {
cur = new Solution();
return cur;
} else {
return cur;
}
}
};
Solution *Solution::cur; //intialization