gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:43:01 24 4
gpt4 key购买 nike

假设 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 classstruct 在所有方面都相同,除了成员变量和函数的默认访问 - 包括继承,正如您所指出的。

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

关于c++ - 结构和类在 C++ 中真的是等价的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com