structDateStruct// 成员默认是公有的{intmonth{};// public by default, can be accessed by anyoneintday{};// public by default, can be accessed by anyoneintyear{};// public by default, can be accessed by anyone};intmain(){DateStructdate;date.month=10;date.day=14;date.year=2020;return0;}
classDateClass// members are private by default{intm_month{};// private by default, can only be accessed by other membersintm_day{};// private by default, can only be accessed by other membersintm_year{};// private by default, can only be accessed by other members};intmain(){DateClassdate;date.m_month=10;// errordate.m_day=14;// errordate.m_year=2020;// errorreturn0;}
classDateClass{public:// note use of public keyword here, and the colonintm_month{};// public, can be accessed by anyoneintm_day{};// public, can be accessed by anyoneintm_year{};// public, can be accessed by anyone};intmain(){DateClassdate;date.m_month=10;// okay because m_month is publicdate.m_day=14;// okay because m_day is publicdate.m_year=2020;// okay because m_year is publicreturn0;}
因为 DateClass 的成员现在是公有的了,因此它们可以被 main()访问。
public 关键字及其后面的分号,称为成员访问修饰符,它可以设置谁可以访问对应的成员。每个成员都可以从其前面的成员访问修饰符获取对应的访问等级(如果没有对应的修饰符,则使用默认的访问修饰符)。
#include<iostream>classDateClass// members are private by default{intm_month{};// private by default, can only be accessed by other membersintm_day{};// private by default, can only be accessed by other membersintm_year{};// private by default, can only be accessed by other memberspublic:voidsetDate(intmonth,intday,intyear)// public, can be accessed by anyone{// setDate() can access the private members of the class because it is a member of the class itselfm_month=month;m_day=day;m_year=year;}voidprint()// public, can be accessed by anyone{std::cout<<m_month<<'/'<<m_day<<'/'<<m_year;}};intmain(){DateClassdate;date.setDate(10,14,2020);// okay, because setDate() is publicdate.print();// okay, because print() is publicstd::cout<<'\n';return0;}
#include<iostream>classDateClass// members are private by default{intm_month{};// private by default, can only be accessed by other membersintm_day{};// private by default, can only be accessed by other membersintm_year{};// private by default, can only be accessed by other memberspublic:voidsetDate(intmonth,intday,intyear){m_month=month;m_day=day;m_year=year;}voidprint(){std::cout<<m_month<<'/'<<m_day<<'/'<<m_year;}// Note the addition of this functionvoidcopyFrom(constDateClass&d){// Note that we can access the private members of d directlym_month=d.m_month;m_day=d.m_day;m_year=d.m_year;}};intmain(){DateClassdate;date.setDate(10,14,2020);// okay, because setDate() is publicDateClasscopy{};copy.copyFrom(date);// okay, because copyFrom() is publiccopy.print();std::cout<<'\n';return0;}
该例中包含一个 C++ 中常被忽略或误解的细节,访问控制是工作在类的层面,而不是对象层面。 这就意味着如果一个函数可以访问类中的某个私有成员,那么该类所有对象中的该私有成员也都能够被该函数访问。