深入理解C++11 2.8 非静态成员的sizeof
2019-08-08 本文已影响0人
zinclee123
首先明确一点,sizeof是运算符,类似加减乘除。在C++98中,对非静态成员变量使用sizeof是不能够通过编译的。如:
struct People {
public:
int hand;
static People *all;
};
int main(){
People p;
cout << sizeof(p.hand) << endl; // C++98通过 C++11通过
cout << sizeof(People::all) << endl; // C++98通过 C++11通过
cout << sizeof(People::hand) << endl; // C++98错误 C++11通过
return 0;
}
在C++98中,只有静态成员,或者对象的实例才能对其成员记性sizeof操作,因此为了实现对非静态成员变量使用sizeof,在C++98中会使用:
sizeof(((People*)0)->hand);