值得注意的是,唯一的区别是:在公共类的关键词。我们将讨论它的功能在下一课。
就像一个struct定义,一个类的定义并没有宣布任何内存。它只定义了类看起来像。为了使用一个类,该类类型必须声明一个变量:
1
2
3
4
5
6
|
Date cToday;
// declare a variable of class Date
// Assign values to our members using the member selector operator (.)
cToday.m_nMonth = 10;
cToday.m_nDay = 14;
cToday.m_nYear = 2020;
|
在C++中,当我们声明一个类的变量,我们叫它实例化的类。变量本身被称为该类的一个实例。一个类类型的变量也被称为一个对象。
成员函数
除了保持数据,类也可以包含的功能!这是我们的日期类用一个函数来设置日期:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class
Date
{
public
:
int
m_nMonth;
int
m_nDay;
int
m_nYear;
void
SetDate(
int
nMonth,
int
nDay,
int
nYear)
{
m_nMonth = nMonth;
m_nDay = nDay;
m_nYear = nYear;
}
};
|
1
2
|
Date cToday;
cToday.SetDate(10, 14, 2020);
// call SetDate() on cToday
|
请注意,在setdate()原结构的版本,我们需要通过结构自身的setdate()函数作为第一个参数。否则,setdate()不知道我们想做什么datestruct。
然而,在我们的setdate()类版本,我们不需要通过今天来setdate()!因为setdate()是在今天,在setdate()成员变量是指今天的成员变量!因此,内部功能setdate(),m_nday实际上指的是ctoday.m_nday。如果我们把ctomorrow。setdate(),里面的setdate() m_nday将引用ctomorrow.m_nday。
使用“m_”前缀的成员变量有助于区分成员变量的函数的参数或局部内部成员函数变量。这有几个原因是有用的。首先,当我们看到一个分配与“m_”前缀的变量,我们知道我们正在改变类的状态。第二,不同功能的参数和局部变量,并在函数声明,成员变量是在类定义中声明的。因此,如果我们想知道如何与“m_”前缀声明一个变量,我们知道我们应该在类定义中而不是在函数。
按照惯例,类名称必须以一个大写字母。
这里的另一个类的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
#include <iostream>
class
Employee
{
public
:
char
m_strName[25];
int
m_nID;
double
m_dWage;
// Set the employee information
void
SetInfo(
char
*strName,
int
nID,
double
dWage)
{
strncpy
(m_strName, strName, 25);
m_nID = nID;
m_dWage = dWage;
}
// Print employee information to the screen
void
Print()
{
using
namespace
std;
cout <<
"Name: "
<< m_strName <<
" Id: "
<<
m_nID <<
" Wage: $"
<< m_dWage << endl;
}
};
int
main()
{
// Declare two employees
Employee cAlex;
cAlex.SetInfo(
"Alex"
, 1, 25.00);
Employee cJoe;
cJoe.SetInfo(
"Joe"
, 2, 22.25);
// Print out the employee information
cAlex.Print();
cJoe.Print();
return
0;
|