成员函数访问和封装
object-oriented programming 面向对象的编程要求我们需要对一些函数进行封装,并将成员变量权限设置为私有,是为了利用黑箱原理,the separation of interface and implementation is extremely useful because it allows us to use objects without understanding how they work. This vastly reduces the complexity of using these objects, and increases the number of objects we’re capable of interacting with.
The separation of implementation and interface is useful in programming
Encapsulation
1.encapsulated classes are easier to use and reduce the complexity of your programs
在类中如何定义数组利用:C-style strings, std::array, std::vector, std::map, std::list等方法我们不用过多的关心
2.encapsulated classes help protect your data and prevent misuse
外部函数无法访问私有成员
3.encapsulated classes are easier to change
当成员函数未发生改变时,仅改变成员变量的类型,主函数的调用结果相同
如:int -> int [ ]
4.encapsulated classes are easier to debug
当编译程序时程序出现错误,可能是某个变量的引起,如果是全局变量或局部变量我们需要设置断点来检测哪个变量出现了错误,但使用类之后仅需监测类中的成员变量,因为这些变量外部成员函数无法访问
Access functions
Access functions typically come in two flavors: getters and setters. Getters (also sometimes called accessors) are functions that return the value of a private member variable. Setters (also sometimes called mutators) are functions that set the value of a private member variable.
例如:
class Date
{
private:
int m_month;
int m_day;
int m_year;
public:
int getMonth() { return m_month; } // getter for month
void setMonth(int month) { m_month = month; } // setter for month
int getDay() { return m_day; } // getter for day
void setDay(int day) { m_day = day; } // setter for day
int getYear() { return m_year; } // getter for year
void setYear(int year) { m_year = year; } // setter for year
};
**** Getters should provide “read-only” access to data. Therefore, the best practice is that they should return by value or const reference (not by non-const reference).
recommend a pragmatic approach
. when create classes, consider the following
If nobody outside your class needs to access a member, don’t provide access functions for that member.
If someone outside your class needs to access a member, think about whether you can expose a behavior or action instead (e.g. rather than a setAlive(bool) setter, implement a kill() function instead).
If you can’t, consider whether you can provide only a getter.