我正在寻找有关C ++中静态方法的信息。 我搜索过但老实说无法清楚地理解一件事。
静态函数是那些仅包含静态数据成员的函数吗?
答案 0 :(得分:2)
类的静态方法没有this
指针。这意味着他们无法访问实例成员数据。方法(静态或其他)不包含数据成员。 (但是,它们可以在堆栈或堆上声明变量。)
静态方法通常使用类名(myClass::foo()
)调用,因为您不必声明类的实例以使用它们,但可以使用实例(myInstance.foo()
)调用还
答案 1 :(得分:2)
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类似于类,除了struct成员默认是公共的,这也适用于struct。
使用静态函数和变量的一个原因是使用factory pattern为类创建对象工厂。另一个用途是使用Singleton Pattern。