gpt4 book ai didi

c++ 使用成员选择运算符(. 或 –>)访问静态成员函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:16:56 24 4
gpt4 key购买 nike

我刚刚注意到我们可以通过成员选择运算符(. 或 –>)访问 c++ 静态成员函数

例如:

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
}
};

这里是使用方法

  StaticTest test;
printf_s("%d\n", StaticTest::count()); //#2
printf_s("%d\n", test.GetY());
printf_s("%d\n", test.count()); //#3 accessing with . operator
test.SetY();
  1. #1 和#3 的用例是什么?
  2. #2 和#3 有什么区别?

在成员函数中访问静态成员函数的#1 的另一种风格是

  void SetY(){
y = count(); //however, I regard it as
} // StaticTest::count()

但现在它看起来更像 this->count()。两种调用方式有区别吗?

谢谢

最佳答案

看看这个question .

根据标准(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.

因此,当您已经拥有一个对象并在其上调用静态方法时,使用类成员访问语法没有区别。

但是如果您需要先创建对象(通过直接实例化对象,或者通过调用某个函数),那么这个创建过程当然会占用一些额外的时间和内存。然而,this-Pointer 永远不会传递给静态函数,调用本身总是相同的,无论它是如何编写的。

关于c++ 使用成员选择运算符(. 或 –>)访问静态成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8642219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com