美文网首页
深入理解C++11 2.8 非静态成员的sizeof

深入理解C++11 2.8 非静态成员的sizeof

作者: zinclee123 | 来源:发表于2019-08-08 19:05 被阅读0次

    首先明确一点,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);
    

    相关文章

      网友评论

          本文标题:深入理解C++11 2.8 非静态成员的sizeof

          本文链接:https://www.haomeiwen.com/subject/wtsfjctx.html