数据域采用public的形式有2个问题 (1) First, data may be tampered. ( 数据会被类外的方法篡改) (2) Second, it makes the class difficult to maintain and vulnerable to bugs. ( 使得类难于维护,易出现bug)
class Circle { public: double radius; //…… }; // main() { circle1.radius=5; //类外代码可修改public数据将radius放入私有区域进行封装,使得从外部不能直接访问radius。
如果我们想对radius进行赋值或者读取radius就需要使用到访问器与更改器。
(1) get function is referred to as a getter (获取器,or accessor), (2) set function is referred to as a setter (设置器,or mutator).
returnType getPropertyName()
bool isPropertyName()
void setPropertyName(dataType propertyValue)、
The process of removing physical, spatial, or temporal details or attributes in the study of objects or systems in order to more closely attend to other details of interest ( 在研究对象或系统时,为了更加专注于感兴趣的细节,去除对象或系统的物理或时空细节/ 属性的过程叫做抽象)
A language mechanism for restricting direct access to some of the object’s components.( 一种限制直接访问对象组成部分的语言机制) A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data ( 一种实现数据和函数绑定的语言构造块)
抽象: 提炼目标系统中我们关心的核心要素的过程 封装: 绑定数据和函数的语言构造块,以及限制访问目标对象的内容的手段
The data members are accessible to all constructors and functions in the class. (数据成员可被类内所有函数访问) Data fields and functions can be declared in any order in a class. (数据域与函数可按任意顺序声明)
If a local variable has the same name as a data field: (若成员函数中的局部变量与某数据域同名)
(1) the local variable takes precedence ( 局部变量优先级高:就近原则) (2) the data field with the same name is hidden. ( 同名数据域在函数中被屏蔽)
How do you reference a class’s hidden data field in a function? (如何在函数内访问类中被屏蔽的数据域)? 可以使用 this 关键字 This 关键字的特性 (1) a special built-in pointer ( 特殊的内建指针)this指针不需要声明也不需要赋初值。 (2) references to the calling object. ( 引用当前函数的调用对象)
If the parameter of a member function has the same name as a private class variable, then the parameter should have underscore suffix.
若类的成员函数参数与私有成员变量名相同,那么参数名应加下划线后缀
例:
class SomeClass { int length; public: void setLength( int length_ );1、我们不可以修改this指针的值,使之指向另外一个对象 2、this指针是自动初始化的、this指针指向调用当前函数的对象、我们不可以显示地声明this指针。