c++ - 静态类成员不是与 this 指针没有关联吗?

标签 c++ this c++17 static-members this-pointer

举个例子:

SomeClass.h

class Foo {
public:
    static int bar;
    int x;
    void someFunc() {
        this->x = 5;
        this->bar = 9;
    }
};

SomeClass.cpp

int Foo::bar = 0;

ma​​inc.pp

#include <iostream>
#include "SomeClass.h"

int main() {
    Foo f;
    f.someFunc();

    std::cout << "f.x = " << f.x << '\n';
    std::cout << "f.bar = " << f.bar << '\n';
    return 0;
}

使用 Visual Studio 2017CE 编译构建。

输出

f.x = 5
f.bar = 9

但是根据cppreference:static

Static members of a class are not associated with the objects of the class: they are independent variables with static or thread (since C++11) storage duration or regular functions.

现在关于静态成员函数,他们声明:

Static member functions are not associated with any object. When called, they have no this pointer.

我只是想澄清一下:我原以为静态成员和静态函数成员都没有与之关联的 this 指针...

最佳答案

它们与您示例中的 this 指针无关。相反,它们恰好可以通过 this 指针访问(出于同样的原因,f.bar = 10; 也是合法的)。

C++ 标准明确涵盖了这一点。请参阅“[class.static] 静态成员”部分(http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf),其中指出:

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 (8.5.1.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.

[ Example:

struct process {
  static void reschedule();
};
process& g();

void f() {
  process::reschedule(); // OK: no object necessary
  g().reschedule(); // g() is called
}

— end example ]

关于c++ - 静态类成员不是与 this 指针没有关联吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56763628/

相关文章:

c++ - 关于数据对齐的困惑

关于cout和cin的C++简单代码问题

c++ - seekg 不转到文件开头

c++ - 使用 -O3 的两个等效函数的公平计时

javascript - 对象函数中的 this 关键字

c++ - 模板模板参数推演指南

c++ - 基准可变参数模板函数调用

javascript - 为什么在同一语句中调用时括号会保留它

javascript - Angularjs 在 ng-click 函数中访问此元素

c++ - 调用超时方法