C++中Encapsulation的使用

Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse.

Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes.

Encapsulation is a process of wrapping of data and methods in a single unit. It is achieved in C++ language by class concept.

Encapsulation is the process of combining data and functions into a single unit called class.Using the method of encapsulation, the programmer cannot directly access the data. Data is only accessible through the functions existing inside the class.Data encapsulation led to the important concept of data hiding. Data hiding is the implementation details of a class that are hidden from the user. The concept of restricted access led programmers to write specialized functions or methods for performing the operations on hidden members of the class. Attention must be paid to ensure that the class is designed properly.

The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.

封装的目的是增强安全性和简化编程,使用者不必了解具体的实现细节,而只是通过外部接口,特定的访问权限来使用类的成员。通过封装使一部分成员充当类与外部的接口,而将其他的成员隐蔽起来,这样就达到了对成员访问权限的合理控制,使不同类之间的相互影响减少到最低限度,进而增强数据的安全性和简化程序的编写工作。

C++通过类来实现封装性,把数据和与这些数据有关的操作封装在一个类中,或者说,类的作用是把数据和算法封装在用户声明的抽象数据类型中。

         实际上用户往往并不关心类的内部是如何实现的,而只需知道调用哪个函数会得到什么结果,能实现什么功能即可。在声明了一个类以后,用户主要是通过调用公用的成员函数来实现类提供的功能。因此,公用成员函数是用户使用类的公用接口(public interface),或者说是类的对外接口。类中被操作的数据是私有的,实现的细节对用户是隐蔽的,这种实现称为私有实现(private implementation)。这种“类的公用接口与私有实现的分离”形成了信息隐蔽。

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "encapsulation.hpp"
#include <iostream>

/
// reference: http://www.tutorialspoint.com/cplusplus/cpp_data_encapsulation.htm
class Adder{
public:
	// constructor
	Adder(int i = 0)
	{
		total = i;
	}
	// interface to outside world
	void addNum(int number)
	{
		total += number;
	}
	// interface to outside world
	int getTotal()
	{
		return total;
	};
private:
	// hidden data from outside world
	int total;
};

int test_encapsulation1()
{
	Adder a;

	a.addNum(10);
	a.addNum(20);
	a.addNum(30);

	std::cout << "Total " << a.getTotal() << std::endl;
	return 0;
}
GitHubhttps://github.com/fengbingchun/Messy_Test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值