【问题标题】:I know struct is a class but the code says No我知道 struct 是一个类,但代码说 No
【发布时间】:2017-05-18 20:33:39
【问题描述】:

我试图让朋友相信struct 只是现代 C++ 中的class。经过一番争论和资源交流(包括一些SO Q&A),我萌生了用代码来证明的想法,于是我写了:

class A {};
struct B {};

int main()
{
    cout << (is_class<A>::value ? "Yes" : "No") << "\n";  // output Yes
    cout << (is_class<B>::value ? "Yes" : "No") << "\n";  // output Yes

    cout << (is_same<A,B>::value ? "Yes" : "No") << "\n"; // output No ???
}

如您所见,我对第三行 cout 的输出感到惊讶。所以,我现在被困在这里,我不知道我是否正确。

struct 是不是 class?
为什么代码显示两个不同的东西?

更新:

我很了解结构和类之间的区别。让我感到困惑的是is_class 和is_same 之间的区别,如答案所示。如果不在这里问我该怎么办??? 这个网站是干什么用的?为什么有些用户倾向于声称问题没有用,甚至没有发表评论来说明它不符合提问政策的地方?

请记住,我们并不是所有人都能说一口流利的英语。并不是所有人都有多年的经验。

感谢所有回答或评论的人。

【问题讨论】:

标签: c++ class struct types typetraits


【解决方案1】:

起初,你是对的。 结构只是一个类。

一些迹象:

1- 您可以转发声明其中一个,然后用另一个定义它(尽管一些编译器可能会发出警告)。

class A;     // declaration of A with class
struct A { /* definition of A with struct */ } ;

2- is_class&lt;&gt; 对两者都返回 true。
3- &lt;type_traits&gt; 中没有 is_struct&lt;&gt;。
4- 在大多数情况下,这两个关键字是可以互换的。 (例如:在作用域枚举中)。

但是,它们有重要的语法差异:

struct

  • 默认授予其成员公共访问权限。
  • 如果不使用 C++ 功能,则向后兼容 C。

class

  • 默认授予其成员私有访问权限。
  • 与 C 不兼容。

使用哪一个是约定和/或方便的问题。

一般来说,我更喜欢使用struct 作为数据(记录)的聚合。和class 用于其他用途。

现在我们来回答你的第二个问题:

为什么代码显示两个不同的东西?

它没有。

因为is_class&lt;&gt; 不是关于类型,而是关于类型类别。 (即is_class&lt;x&gt; 检查type x 是否是一个类)而is_same&lt;&gt; 是关于类型本身((即is_same&lt;x, y&gt; 检查type x 是否为是否与 type y 相同))

如果您将测试代码中的struct 更改为class,is_same&lt;&gt; 仍会输出“No”,因为A 是一种类型,B 是另一种类型,即使它们都具有相同的类型类别这是class。

根据您的代码:

A a;  // a is of type A
B b; // b is of type B
// Can we say that a and b of the same type?
// No. And this is what is_same<> checks.

【讨论】:

【解决方案2】:

您对std::is_same&lt;&gt; 的用途感到困惑。

来自http://en.cppreference.com/w/cpp/types/is_same:

如果 T 和 U 使用相同的 const-volatile 命名相同的类型 限定条件,提供等于 true 的成员常量值。 否则值为 false。

显然A 和B 是不同的类;最后一句话,我暗示你确实是正确的,因为struct 与class 相同;区别在于struct 对其成员的默认访问权限为public,而class 的默认访问权限为private。

不要相信我的话,C++ 标准在 10.1.7.3 Elaborated type specifiers [dcl.type.elab] 中声明了以下内容:

[...] class 或 struct class-key 应用于引用 使用类或结构类键声明的类。

参考:http://eel.is/c++draft/dcl.type.elab

【讨论】:

    【解决方案3】:

    这与struct 与class 无关。

    cout << (is_class<A>::value ? "Yes" : "No") << "\n";  // output Yes
    

    是的,因为A 是一个类。

    cout << (is_class<B>::value ? "Yes" : "No") << "\n";  // output Yes
    

    是的,因为B 也是一个类(it really is)。

    cout << (is_same<A,B>::value ? "Yes" : "No") << "\n"; // output No ???
    

    不,因为他们不是同一个班级。

    A 和B 是两种不同的类型。

    这是std::is_same,而不是std::is_similar。

    【讨论】:

    • 感谢 @BoundaryImposition 的精彩帖子。我检查了它们,它们真的很好。所以,如果我需要检查这样的事情,我可以使用类似:if (is_class(A) &amp;&amp; (is_class(B))。 ...我寻找is_similar,但它不存在。所以我想你是为了清楚起见而提到它。但是如果我需要这样的功能呢?
    • @KamalZidan:是的。是的,std::is_similar 不存在;据我所知,没有办法(或理由)实施它。
    猜你喜欢
    • 2014-10-27
    • 2016-04-24
    • 2015-04-30
    • 2021-08-22
    • 2023-02-03
    • 1970-01-01
    • 2019-04-15
    • 2021-07-06
    • 2022-01-22
    相关资源
    最近更新 更多