在C + +提供了一些基本的数据类型(如char,int,长,浮动,双,等),往往是足以解决相对简单的问题,很难用这些类型的解决复杂的问题。一个C++的更有用的功能是定义自己的数据类型,更好地对应于被制定后,问题的能力。你已经看到了如何枚举类型和结构可用于创建您自己的自定义数据类型。
这是一个用来举行日期的结构的一个例子:
1
2
3
4
5
6
|
struct
DateStruct { int
nMonth; int
nDay; int
nYear; }; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//
Declare a DateStruct variable DateStruct
sToday; //
Initialize it manually sToday.nMonth
= 10; sToday.nDay
= 14; sToday.nYear
= 2020; //
Here is a function to initialize a date void
SetDate(DateStruct &sDate, int
nMonth, int
nDay, int
Year) { sDate.nMonth
= nMonth; sDate.nDay
= nDay; sDate.nYear
= nYear; } //
Init our date to the same date using the function SetDate(sToday,
10, 14, 2020); |
在面向对象编程的世界,我们常常希望我们的类型不仅保存数据,但提供的功能,使用数据和。在C++中,这是通过class关键字。用class关键字定义了一个新的用户定义的类型称为一类。
等级
在C++中,类是非常喜欢结构,除了类提供了更多的权力和灵活性。事实上,下面的结构与类别实际上是相同的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
struct
DateStruct { int
nMonth; int
nDay; int
nYear; }; class
Date { public : int
m_nMonth; int
m_nDay; int
m_nYear; }; |