C++ Struct编译成class?

C++ Struct is compiled into class?

我正在研究 C++。我正在使用 MVSV 2010。

当我编译源代码并使用 -d1reportAllClassLayout.

转储所有 class 的内存布局时

比如我声明了struct:

struct my_struct{
    int a;
};

struct的内存布局如下:

class my_struct size(4):
    +---
0   | a
    +---

这是否意味着 C++ 编译器在所有方面都将结构视为与 class 相同? (适用于默认访问说明符)

如果那样,那么struct的构造函数和析构函数呢?

结构体有默认的构造函数和析构函数吗?它类似于 Class?

非常感谢您的支持,

在 C++ 中 class 和结构(几乎)完全相同。它们之间唯一的区别是 class 默认是 private 而 struct 默认是 public

在 C++ 中,class 的概念定义如下

class-specifier:
    class-head { member-specificationopt}

其中 class-head 依次定义为

class-head:
    class-key attribute-specifier-seqopt class-head-name class-virt-specifieropt base-clauseopt
    class-key attribute-specifier-seqopt base-clauseopt

哪里

class-key:
    class
    struct
    union

因此一个结构是 class 和 class-key struct

和(C++ 标准 12.1 构造函数)

4 A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4). An implicitly-declared default constructor is an inline public member of its class...

由于结构是 class 并且没有用户声明的构造函数,因此编译器隐式声明了这样的构造函数。

这可能只是意味着 d1reportAllClassLayout 报告它们相同

引用自Stroustrup's FAQ

A well-designed class presents a clean and simple interface to its users, hiding its representation and saving its users from having to know about that representation. If the representation shouldn't be hidden - say, because users should be able to change any data member any way they like - you can think of that class as "just a plain old data structure"; for example:

struct Pair {
   string name, value; };

结构是相似或不同数据类型的集合。 类 通过允许在结构中包含函数来扩展结构的范围。现在,如果一个结构只是数据类型的集合,那么您肯定可以像构造函数一样将它们初始化为某个默认值,否则编译器会像 Vlad 的回答中提到的那样隐式地为您完成它,但您不需要任何析构函数和默认情况下没有析构函数。