访问类的成员

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值