1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Date
{
public:
int m_nMonth; // public
int m_nDay; // public
int m_nYear; // public
};
int main()
{
Date cDate;
cDate.m_nMonth = 10; // okay because m_nMonth is public
cDate.m_nDay = 14; // okay because m_nDay is public
cDate.m_nYear = 2020; // okay because m_nYear is public
return 0;
}
Because Date’s members are now public, they can be accessed by main().
一个类和结构的主要区别是,类可以显式地使用访问修饰符,限制谁可以访问类的成员。C++提供了3种不同的访问说明符关键词:公共,私人,和保护。我们将讨论保护访问说明符当我们盖的继承。
这是一种使用所有三个访问说明符例:
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
class Access
{
int m_nA; // private by default
int GetA() { return m_nA; } // private by default
private:
int m_nB; // private
int GetB() { return m_nB; } // private
protected:
int m_nC; // protected
int GetC() { return m_nC; } // protected
public:
int m_nD; // public
int GetD() { return m_nD; } // public
};
int main()
{
Access cAccess;
cAccess.m_nD = 5; // okay because m_nD is public
std::cout << cAccess.GetD(); // okay because GetD() is public
cAccess.m_nA = 2; // WRONG because m_nA is private
std::cout << cAccess.GetB(); // WRONG because GetB() is private
return 0;
}