结构和类在C++中是否真的相同?

ar2*_*015 3 c++ class

假设struct类似于class除了默认成员的隐私,为什么下面的代码不会编译?

#define class struct
#include <iostream>


int main()
{
     return 0;
}
Run Code Online (Sandbox Code Playgroud)

更新

In file included from /usr/include/c++/7/bits/stl_algobase.h:61:0,
                 from /usr/include/c++/7/vector:60,
                 from main.cpp:5:
/usr/include/c++/7/bits/cpp_type_traits.h:86:18: error: ‘struct std::_Sp’ is not a valid type for a template non-type parameter
   template<class _Sp, class _Tp>
                  ^~~
compilation terminated due to -Wfatal-errors.
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 9

代码的行为未定义:C++标准不允许重新定义关键字.

也许特定的失败是由于template<class T>有效的语法而template<struct T>不是?预处理器步骤似乎破坏了<iostream>您平台上的实现.

(A classstruct是相同的在各方面除了成员变量和函数的默认访问-包括继承,正如你指出.

C++标准允许您将声明转发为a struct并实现为a class,反之亦然,尽管有些编译器; 例如旧版本的MSVC; 不允许这样做.)

  • 作为关键字,它们也有另一个区别:你可以说`template <class T>`,但你不能说`template <struct T>`. (2认同)