访问类的成员

来源:互联网 发布:js脚本注入攻击 编辑:程序博客网 时间:2024/06/09 19:47
1234567891011121314151617class 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种不同的访问说明符关键词:公共,私人,和保护。我们将讨论保护访问说明符当我们的继承

这是一种使用所有三个访问说明符

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


0 0
原创粉丝点击