访问功能
访问函数是一个短的公共功能,其工作是返回私有成员变量的值。例如,在上述的String类,你可能会看到这样的东西:
class String
{
private:
char *m_chString; // a dynamically allocated string
int m_nLength; // the length of m_chString
public:
int GetLength() { return m_nLength; }
};
getlength()是访问函数简单地返回m_nlength价值。
访问功能,通常有两种:getters和setters。干将是函数简单地返回私有成员变量的值。制定功能,只需设置一个私有成员变量的值。
这里有一个例子类,具有一定的getters和setters:
class Date
{
private:
int m_nMonth;
int m_nDay;
int m_nYear;
public:
// Getters
int GetMonth() { return m_nMonth; }
int GetDay() { return m_nDay; }
int GetYear() { return m_nYear; }
// Setters
void SetMonth(int nMonth) { m_nMonth = nMonth; }
void SetDay(int nDay) { m_nDay = nDay; }
void SetYear(int nYear) { m_nYear = nYear; }
};