结构和类在C++中真的等价吗?

Are structures and classes really equivalent in C++?

本文关键字:真的 C++ 结构      更新时间:2023-10-16

假设除了默认成员隐私之外,structclass相似,为什么下面的代码不编译?

#define class struct
#include <iostream>

int main()
{
return 0;
}

更新

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.

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

也许具体的失败是由于template<class T>是有效的语法,但template<struct T>不是?预处理器步骤似乎破坏了平台上<iostream>的实现。

(正如您所指出的,除了成员变量和函数的默认访问(包括继承(之外,classstruct在所有方面都是相同的。

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

classstruct是等效的(默认隐私除外(

但是语法不允许在模板中struct

template <struct S> // Invalid
/*..*/

template <class C> // valid
/*..*/

template <typename T> // valid
/*..*/

定义成员时的行为是相同的。

但是,classstruct并非在所有情况下都是同义词。

template<class T>template <typename T>的同义词。您的#define会将其变成template <struct T>,这是不允许的。我认为这就是为什么您在标准标题中的模板上出现错误的原因。

除了其他答案,

要入侵私有可见性范围,侵入性最小的方法可能是将标头复制到代码库中(确保它在-I路径中排在第一位(,并使其中一个类成为需要黑客攻击的第三方 API 类的朋友。这将是我临时修补次优第三方 API 以供生产使用的工具。

另一种更"牛仔"的方式是#define private public一些有限的范围。这个我可能不会在生产代码库中做。