什么是静态方法?如何以及何时使用它们
What are static methods? How and when are they used?
我正在寻找有关C++静态方法的信息。我搜索了一下,但老实说,我无法清楚地理解一件事。
静态函数是那些只包含静态数据成员的函数吗?
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
当然,由于结构类似于类,只是结构成员默认是公共的,这也适用于结构。
使用静态函数和变量的一个原因是使用工厂模式为类创建对象工厂。 另一个用途是单例模式。
类的静态方法没有this
指针。 这意味着它们无法访问实例成员数据。 方法(静态或其他(不包含数据成员。 (但是,它们可以在堆栈或堆上声明变量。
静态方法通常用类名(myClass::foo()
(调用,因为你不必声明类的实例来使用它们,但也可以用实例(myInstance.foo()
(调用。
相关文章:
- 尝试了解在导入的静态方法上使用删除方法时的错误
- 如何通过命名空间调用非静态方法
- 如何在没有实例的情况下获取非静态方法的类型?
- 调用从模板派生的类的静态方法,而不指定模板
- 如何在 c++ 中异步调用静态方法?
- C++ 将静态方法转换为简单方法
- 何时使函数成为类成员函数C++?
- 从另一个标头中的标头调用静态方法
- C++中静态方法的局部变量范围
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 使用本机 JNI 静态方法实现C++ Java 运行时错误
- 当只有静态方法受到影响时,如何解决C++中的链接器错误?
- 静态变量在同一个翻译单元中被静态方法使用时是否保证被初始化?
- 为什么链接器报告全局函数的乘法定义符号,而不是类静态方法
- 从部分专用模板方法调用模板非静态方法
- 如何使用 c++ 在 cocos2dx 中定义非静态方法
- 使用 CMake 的静态方法链接错误
- 在子类上调用模板化静态方法时获取类的类型名
- 仅具有公共静态方法的帮助程序类
- 什么是静态方法?如何以及何时使用它们