结构和类在C++中真的等价吗?
Are structures and classes really equivalent in C++?
假设除了默认成员隐私之外,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>
的实现。
(正如您所指出的,除了成员变量和函数的默认访问(包括继承(之外,class
和struct
在所有方面都是相同的。
C++ 标准允许您将声明转发声明为struct
并作为class
实现,反之亦然,尽管某些编译器(例如旧版本的 MSVC(不允许这样做。
class
和struct
是等效的(默认隐私除外(
但是语法不允许在模板中struct
:
template <struct S> // Invalid
/*..*/
而
template <class C> // valid
/*..*/
或
template <typename T> // valid
/*..*/
定义成员时的行为是相同的。
但是,class
和struct
并非在所有情况下都是同义词。
template<class T>
是template <typename T>
的同义词。您的#define
会将其变成template <struct T>
,这是不允许的。我认为这就是为什么您在标准标题中的模板上出现错误的原因。
除了其他答案,
要入侵私有可见性范围,侵入性最小的方法可能是将标头复制到代码库中(确保它在-I
路径中排在第一位(,并使其中一个类成为需要黑客攻击的第三方 API 类的朋友。这将是我临时修补次优第三方 API 以供生产使用的工具。
另一种更"牛仔"的方式是#define private public
一些有限的范围。这个我可能不会在生产代码库中做。
相关文章:
- 在决定是通过参考还是通过价值时,尺寸真的是一个问题吗
- 字节真的是最小可寻址单元吗
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 如何在 std::vector 中找到<bool>哪些索引是真的?
- std::string 的对象真的可以移动吗?
- 在这种情况下,我真的复制了字节还是复制了字符?
- int8_t和uint8_t真的是整数吗?它们有什么用?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 查找不等式为真的次数时出现问题
- 考虑到其他好处,关键字'auto'真的有助于简化调试C++吗?
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 在为嵌套类定义行外友元时,我真的必须打破封装吗?
- 你如何理解"std: :forward is just syntactic sugar"?这是真的吗?
- "std::forward"和"std::move"真的不生成代码吗?
- VS 2017 和 2019 运行 c++ 真的很慢
- 结构和类在C++中真的等价吗?
- 指向数组unique_ptr在调用 release() 后会自动释放动态内存,这是真的吗?
- 运算符重载是否真的需要返回值C++?
- 我想使用 "cout" 命令慢慢打印文本,但我真的找不到任何解决方案
- " sizeof "操作员在编程中真的很重要吗,尤其是在构建大型应用程序时?