【C++】Accessor and Mutator Functions & 函数形参与类私有成员重名的解决方法
来源:互联网 发布:绫野刚 知乎 编辑:程序博客网 时间:2024/06/05 00:30
Accessor and Mutator functions
Definition
- Accessor and mutator functions (a.k.a. set and get functions) provide a direct way to change or just access private variables.
- They must be written with the utmost care because they have to provide the protection of the data that gives meaning to a class in the first place. Remember the central theme of a class: data members are hidden in the private section, and can only be changed by the public member functions which dictate allowable changes.
- 某个变量只能通过公共方法来存取,这种变量叫做accessor或mutator。
- accessor和mutator主要用来实现数据的封装,有了accessor和mutator,我们就可以将数据成员设为私有,所有对它们的读写操作都通过这两个函数来实现。
#include<iostream>#include<string>class student{private: int id;//id这个名称称为accessor存取器或mutator变值器。public: int getId();//accessor function,是只读性质的函数 void setId(int id);//mutator function,是只写性质的函数};
函数形参与类私有成员重名的解决方法
#include<iostream>class retangle{private: double width; double height;public: void setWidth(double width); void setHeight(double height);};
-按照一般做法,我们会这样来实现这两个set函数:
#include<iostream>class retangle{private: double width; double height;public: void setWidth(double width) { width = width;//error return; } void setHeight(double height) { height = height;//error return; }};
但是我们会发现这样是行不通的,会出现编译错误,原因大概是,编译器把两个width和height都当成是传进函数的参数。
这个时候,我们就需要引入this指针来解决这个问题。
#include<iostream>class retangle{private: double width; double height;public: void setWidth(double width) { this->width = width; return; } void setHeight(double height) { this->height = height; return; }};
通过引用this指针,可以明确复制号的左操作数是调用函数的对象里面的width和height,而不是传进去的参数,从而不会引起混淆。
当然了,这种设形参的方法本来就不太好,如果不是题目要求而是自己编程的时候应该尽量避免使用。
0 0
- 【C++】Accessor and Mutator Functions & 函数形参与类私有成员重名的解决方法
- 成员函数的形参 与 成员变量重名
- C++ 类的成员函数形参 与 成员变量 重名
- 类的私有成员变量和私有成员函数
- Java编程中常见的单词翻译 Mutator Methods Accessor Methods
- C语言----函数的形参与实参
- C++中enum枚举类型成员重名问题的解决方法
- java中解决构造函数中成员变量和形参重名的问题
- C#控制台基础 接口的函数成员重名,如何解决
- Python类中的私有成员(私有函数,私有变量)
- Python类中的私有成员(私有函数,私有变量)
- c++子类和父类成员函数重名
- c++子类和父类成员函数重名
- c++子类和父类成员函数重名
- c++子类和父类成员函数重名
- C++类的私有成员变量和函数的隐藏
- QT类的私有成员变量和函数的隐藏
- C++中enum枚举类型成员重名问题的解决方法 - Enum枚举类型的类封装
- hibernate配置文件hibernate.cfg.xml的详细解释
- spark源码学习(六):standalone模式的cluster集群源码解读
- Cocoapods安装步骤
- 从头认识Spring-3.8 简单的AOP日志实现(注解版)-扩展增加检查订单功能,以便记录并检测输入的参数
- 【UVa10054】The Necklace【欧拉回路】
- 【C++】Accessor and Mutator Functions & 函数形参与类私有成员重名的解决方法
- 应用开机启动及相关文档翻译
- 03计算机优秀毕业论文-需求分析
- NU1002 The dependency Microsoft.AspNet.Mvc 5.2.3 in project dotnetstarter does not support framework
- dotfuscator混消生成乱码步骤
- uva 10341 二分搜索
- Android.mk的一些FAQ
- STL面试题
- C 基础——指针函数与函数指针