我刚刚注意到,我们可以通过成员选择运算符(。或–>)访问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和#3的用例是什么?
  • #2和#3有什么区别?

  • 在成员函数中访问静态成员函数的另一种#1样式是
      void SetY(){
        y = count();                             //however, I regard it as
      }                                          // StaticTest::count()
    

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

    谢谢

    最佳答案

    看看这个question

    根据标准(C++ 03,9.4个静态成员):



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

    但是,如果您需要首先创建对象(通过直接在其之前实例化对象或通过调用某些函数),则此创建过程当然会占用一些额外的时间和内存。但是,this-Pointer永远不会传递给静态函数,无论调用如何编写,调用本身始终是相同的。

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

    10-11 22:44
    查看更多