当前位置:网站首页>Classes and objects -- encapsulation

Classes and objects -- encapsulation

2022-06-13 09:25:00 Hezeze

C++ Treat everything as an object , Objects with the same properties belong to a class .

The meaning of encapsulation is : Treat attributes and behaviors as a whole

And C The middle structure is similar to .
A class is divided into three parts : Access right ; attribute ; Behavior
You need to create the corresponding object in the main function
Attributes and behaviors are also collectively referred to as members
attribute = Member attribute = Member variables Behavior = Member functions = Member method

class student {
    
	
	public:								// Access right  
	
	string  s_name;						// attribute  
	string 	s_number;
	
	void writname(string n_name){
    
		s_name=n_name;
	}	
	void writnum(string n_num){
    	
		s_number=n_num;					// Behavior  
	}
	void showstu() {
    
		cout <<" full name :"<<s_name<<endl;
		cout <<" Student number :"<<s_number<<endl;
	}
	
};


int main() {
    
	student a1;
	a1.writname(" Bloom ha "); 
	a1.writnum("18203154");
	a1.showstu();
	return 0; 
}

The second meaning of encapsulation : Access right

The permissions of all members are divided into three categories

  1. Public authority public Member classes can access , You can access
  2. Protection rights protected Member classes can access , No access outside of class ( Then inheritance will learn ) The son can visit
  3. Private rights private Member classes can access , No access outside of class ( The son can't visit )

class And struct

struct The default permission for is public
class The default permission for is private

Privatizing member properties is a bit :

  1. You can control the read and write permissions by yourself
  2. Write permission can detect the validity of data
    This is a struct Structural variables are incomparable ,struct Anyone can modify all the variables at will , And the operation on the structure needs to rewrite a function , Complicate the code .
原网站

版权声明
本文为[Hezeze]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270531584317.html