c++ accessing static member function with member-selection operator (. or –>)
我注意到我们可以通过成员选择运算符来访问C++静态成员函数。或>
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class StaticTest { private: int y; static int x; public: StaticTest():y(100){ } static int count() { return x; } int GetY(){return y;} void SetY(){ y = this->count(); //#1 accessing with -> operator } }; |
以下是如何使用
1 2 3 4 5 6 7 8 | StaticTest test; printf_s("%d ", StaticTest::count()); //#2 printf_s("%d ", test.GetY()); printf_s("%d ", test.count()); //#3 accessing with . operator test.SetY(); |
访问成员函数中静态成员函数的1的另一种样式是
1 2 3 | void SetY(){ y = count(); //however, I regard it as } // StaticTest::count() |
但现在它看起来更像这个->count()。两种风格的电话有什么不同吗?
谢谢
看看这个问题。
根据标准(C++ 03,静态成员9.4):
A static member s of class X may be referred to using the qualified-id
expression X::s; it is not necessary to use the class member access
syntax (5.2.5) to refer to a static member. A static member may be
referred to using the class member access syntax, in which case the
object-expression is evaluated.
所以,当您已经有了一个对象,并且正在对它调用一个静态方法时,那么使用类成员访问语法就没有区别了。
但是,如果您需要首先创建对象(通过直接在前面实例化对象或调用某个函数),那么这个创建过程当然会占用一些额外的时间和内存。然而,这个指针从未被传递给静态函数,调用本身总是相同的,不管它是如何写的。
C++ 03,9.4个静态成员
A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class
member access syntax (5.2.5) to refer to a static member. A static
member may be referred to using the class member access syntax, in
which case the object-expression is evaluated.
我对你第一个问题的答案有点困惑,但关于你第二个问题:
在2(
在3中(
在功能上,没有区别,但是2是调用StaticMethods的首选方法。在不需要的时候生成一个对象就是内存使用不当。