静态 class 成员不是与 this 指针没有关联吗?
Doesn't static class members have no association with the 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;
mainc.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
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 ]
举个例子:
SomeClass.h
class Foo {
public:
static int bar;
int x;
void someFunc() {
this->x = 5;
this->bar = 9;
}
};
SomeClass.cpp
int Foo::bar = 0;
mainc.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
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 ]