Class和Struct的主要区别之一就是class可以明确的使用access specifier来限制谁能访问它的成员。C++提供了3种access specifier关键字: public, private 和 protected. protected 将在介绍完inheritance后讨论。
例1:
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;
}
例中每个成员由前面最近的access specifier来制定访问类型。通常private成员放在最前面。public成员被视为该类的接口。