班上第一名 [英] First member of class

查看:79
本文介绍了班上第一名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以下内容是不好的,但我的印象是班级的第一个成员是班级的起始地址。是不是错了?

I know the following is bad but i was under the impression that the first member of class is the starting address of the class. Is it wrong ?

   class A{
      public:
       int a;
       int b;
   };

   class B{
     public :
       int x;
   };

   int main()
   {
        B *pb=new B();
        A *pa=(A*)pb;
        pa->a++;
   }

我的印象是pb-> x将增加1。它是真的还是不确定的?当我们具有用户定义的构造函数或虚函数时,为什么它会更改?

I was under the impression that pb->x would be incremented by 1. Is it always true or undefined ? Why does it change when we have user defined constructors or virtual functions ?

推荐答案

仅当您的类为standard_layout类型时,这才成立。您可以使用特征类型 is_standard_layout

This holds only true if your class is of standard_layout type. This you can test using the type trait is_standard_layout

 std::cout << std::is_standard_layout<A>::value << '\n';
 std::cout << std::is_standard_layout<B>::value << '\n';

对于其他类,您还有其他信息存储在内存中,这是特定于编译器且未标准化的。您可以查看此问题,其中讨论并显示了一些内存布局。

For other classes, you have additional information stored in memory, which is compiler specific and not standardized. You can have a look at This question where some memory layouts are discussed and showed.

对于第二个示例/问题,标准使用以下引号(5.2.10 / 7,N3337草案):

For your second example/question the standard has the following quote (5.2.10/7, N3337 draft):


可以将对象指针显式转换为其他类型的对象指针。当类型为指向T1的指针的prvalue v转换为类型为指向T2的指针时,如果T1和T2均为标准布局类型(3.9),则
的结果为static_cast(static_cast(v))并且T2的对齐要求并不比T1的对齐要求严格,
或任何一种类型都为空。将类型为指向T1的指针的prvalue转换为指向T2的指针的类型(其中T1和T2是对象类型,并且T2的对齐要求是
,不严格于T1的对齐要求),并返回其原始值。类型产生原始指针值。其他任何此类指针转换的结果均未指定。

An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of type "pointer to T1" is converted to the type "pointer to cv T2", the result is static_cast(static_cast(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment requirements of T2 are no stricter than those of T1, or if either type is void. Converting a prvalue of type"pointer to T1" to the type "pointer to T2" (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.

如果我正确阅读并解释了此内容,则您的示例未指定,因为A的对齐要求比B的对齐要求更大。但是,另一种方法应该可以,例如:

If i read and interpret this correctly, then your example is unspecified, as the alignment requirements of A are bigger that those of B. However, the other way should be ok, e.g:

int main()
{
    A *pa=new A();
    B *pb=reinterpret_cast<B*>(pa);
    pb->x++;
    std::cout << pa->a;
}

这篇关于班上第一名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆