C++ 类中的静态方法,就像 Java 类的静态方法一样,是无需实际实例化对象或类实例即可使用的方法。
使用类的标准非静态方法的唯一方法是创建一个对象或实例化该类的一个实例。然后,当您使用方法时,您正在对特定对象或类的实例进行操作。
静态方法有一些限制。例如,您不能在静态方法中使用this 指针。这是因为类的静态方法不与特定的特定对象相关联。相反,它是一种不与任何特定对象绑定的通用方法。
我对类中静态方法的看法是,当我这样做时,我会创建一个特定的命名空间、类名,然后添加一个只能通过使用该特定命名空间访问的函数。
类中的静态变量是在应用程序启动时创建的,无需创建该类的特定实例即可访问。类的所有实例也共享一个静态变量。
因此,举个不同的例子(即兴表演,因此可能会出现编译错误):
class myAclass {
public:
myAclass(); // constructor
void function1 (int iValueSet); // a standard method
static void functionStatic (int iValueSet); // a static method
private:
int iValue; // an object specific variable
static int iValueStatic; // a class general variable shared by all instances of this class
};
int myAclass::iValueStatic = 0; // init the class static variable
myAclass::myAclass () : iValue (0)
{
}
void myAclass::function1 (int iValueSet)
{
iValue = iValueSet; // set the iValue for this particular object
iValueStatic = iValueSet; // set the shared iValueStatic for all instances
}
void myAclass::functionStatic (int iValueSet)
{
// iValue = iValueSet; // ERROR this is not allowed as iValue is not static
iValueStatic = iValueSet; // works since iValueStatic is static
}
然后如何使用这个类:
myAclass jj; // create an object instance
jj.function1(5); // access the non-static method to change the object data
myAclass::functionStatic(8); // set the static iValueStatic
当然,由于 struct 与 class 相似,只是 struct 成员默认为 public,因此这也适用于 struct。
使用静态函数和变量的一个原因是使用factory pattern 为类创建对象工厂。另一个用途是Singleton Pattern。