假设 struct
除了默认的成员隐私外,类似于 class
,为什么下面的代码不能编译?
#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>
的实现。在您的平台上。
(A class
和 struct
在所有方面都相同,除了成员变量和函数的默认访问 - 包括继承,正如您所指出的。
C++ 标准允许您转发声明为 struct
并作为 class
实现反之亦然,尽管有些编译器;例如旧版本的 MSVC;不允许这样做。)
关于c++ - 结构和类在 C++ 中真的是等价的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475140/