C++为什么使用class而不是struct定义类

本篇内容主要讲解“C++为什么使用class而不是struct定义类”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++为什么使用class而不是struct定义类”吧!

C.8:存在非公有成员时,使用class而不是struct定义类

Reason(原因)

Readability. To make it clear that something is being hidden/abstracted. This is a useful convention.

可读性。明确有些东西是被隐藏或抽象的。这是一个有用的惯例。

Example, bad(反面示例)

struct Date {    int d, m;
   Date(int i, Month m);    // ... lots of functions ...private:    int y;  // year};

如果只是考虑C++语言的规则,这段代码没有任何错误。但是如果从设计的观点来看的话,差不多所有东西都错了。私有数据被也隐藏在距离共有数据很远的位置。数据被分散到类声明的不同部分。不同部分的数据的访问属性也不同。所有的这些都会降低可读性并增加维护的复杂性。

Note(注意)

Prefer to place the interface first in a class, see NL.16.

类的开始部分最好放置接口

Enforcement(实施建议)

Flag classes declared with struct if there is a private or protected member.

如果使用struct关键字声明的类具有私有或保护成员,进行提示。

到此,相信大家对“C++为什么使用class而不是struct定义类”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!