结构继承与C ++中的类继承 [英] Struct inheritance vs class inheritance in C++

查看:140
本文介绍了结构继承与C ++中的类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从此 Q / A 发现结构在C ++中是可继承的,但是它是一个好的做法,还是更喜欢使用类?在哪些情况下是首选,哪些不是?

I just discovered from this Q/A that structs are inheritable in C++ but, is it a good practice, or is it preferable to use classes? In which cases is preferable and in which ones is not?

我从来没有需要这个,但现在我有一堆不同类型的消息,但相同的经度。我得到他们在二进制在一个字符数组,我只是复制他们与memcpy到结构来填充它的字段(我不知道是否甚至可能做到与std :: copy)。

I have never needed this, but now I have a bunch of messages of different types, but same longitude. I got them in binary in a char array, and I just copy them with memcpy to the struct to fill its fields (I don't know if it is even possible to do it with std::copy).

我想这将是巨大的能够继承每个结构从基础结构与公共头,这就是为什么我搜索这个。所以第二个问题是:如果我这样做的类,是否可以做一个memcpy(或std:copy)从缓冲区到一个类?

I guess it would be great to be able to inherit every struct from a base struct with common headers, that is why I searched for this. So a second question would be: if I do this with classes, is it possible to do a memcpy (or std:copy) from a buffer to a class?

推荐答案

是否可以使用按位复制与 struct 类无关。标签,只取决于 struct class is_trivially_copiable 。它们是否在标准(9/6 [class])和中定义,基本上归结为不必声明任何其他特殊成员方法,而不是构造函数

Whether you can use a bitwise copy or not has nothing to do with the struct or class tag and only depends on whether said struct or class is_trivially_copiable. Whether they are is defined in the Standard (9/6 [class]) and it basically boils down to not having to declare any other special member methods than constructors.

标准在3.9 / 2 [basic.types]中允许按位复制

The bitwise copy is then allowed by the Standard in 3.9/2 [basic.types]


对于任何对象无论对象是否保存类型 T T c>,构成对象的底层字节(1.7)可以复制到 char 或unsigned char 。如果将 char unsigned char 数组的内容复制回对象,则对象应随后保持原值。 [例如:

For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char. If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value. [ Example:

#define N sizeof(T)
char buf[N];
T obj; // obj initialized to its original value
std::memcpy(buf, &obj, N); // between these two calls to std::memcpy,
                           // `obj` might be modified
std::memcpy(&obj, buf, N); // at this point, each subobject of `obj`
                           // of scalar type holds its original value

-end example ]

注意:

使用 std :: copy 达到相同的效果:

char const* b = reinterpret_cast<char const*>(&obj);
std::copy(b, b + N, buf);

这篇关于结构继承与C ++中的类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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