请注意,在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;
}

被折叠的 条评论
为什么被折叠?



