C++ Object-Oriented Programming (2nd Edition) Chapter 2 (Characteristics of Classes and Objects) Summary of Knowledge Points

C++ object-oriented programming

参考书目:《C++面向对象程序设计》—— 谭浩强 《C++程序设计:思想与方法》—— 翁惠玉



1. Overview of object-oriented programming methods

1. Definition of object-oriented programming

       The idea of ​​object-oriented programming is similar to the way people deal with problems in daily life. That is, a complex thing always consists of many parts. When people produce cars, they do not design and manufacture the engine first, then design and manufacture the chassis, and then design and manufacture the body and wheels. Instead, they design and manufacture the engine, chassis, body and wheels separately, and finally assemble them. The basic idea of ​​objects.
       Object-oriented programming elements:

  • Object : Any thing in the objective world can be regarded as an object. The object can be a natural object, an organizational structure in society (class, school), or even a graphic, a plan, etc. can be regarded as an object. Complex objects are composed of simple objects, which are the basic units that make up a system . Every object has static and dynamic characteristics . Static features (data) are called attributes , dynamic features (functions) are called actions , and information sent to an object from the outside is generally called a message . Events generally consist of multiple messages.
  • Encapsulation and information concealment : Encapsulate an object and shield some of its attributes and functions from the outside world. These attributes and functions cannot be seen from the outside. Encapsulation has two meanings here: 1) Encapsulate relevant data and operation codes in an object to form a basic unit in the program. Each object is independent of each other and does not interfere with each other. 2) Hiding certain parts of the object from the outside world, leaving only the interface to communicate with the outside world to receive external messages. This method of hiding from the outside world is called information shielding. The public functions in a C++ object are the external interface of the object. The outside world accesses the data members in the object by calling public functions to complete specified operations.
  • Abstraction : Abstraction is a method of expressing the essence of the same type of things. It focuses on the essential characteristics of things. The objects are concrete and can abstract the common characteristics of a group of similar objects to form a class (a class is a group of similar objects in the objective world ) . abstraction and description, which is a collection of objects with the same properties and behavior) . That is, a class is an abstraction of an object, and an object is a concrete instance of the class .
  • Inheritance and reuse : If you have already created a class named A, you now need to create a class named B. The content of class B is basically the same as that of class A, except that some attributes and behaviors are added to class A. In this way, you only need to Just add new content on the basis of class A. This is the inheritance mechanism in object-oriented programming. With software reuse, you can not only use the classes you have created in the past, but also use the classes placed by others in the class library to create classes, which greatly shortens the software development cycle.
  • Polymorphism : When multiple similar but not identical objects receive the same message from the outside world, they each perform different operations. This phenomenon is called polymorphism. The so-called polymorphism in C++ refers to: a new class generated by inheritance, whose objects will respond differently to the same message. For example, in Windows, when you double-click a file object with the mouse, if it is an executable file, the program in the file will be executed. If it is a text file, an editor will be started to open the file. This is an object-oriented program. A practical example of polymorphism in design.

2. Characteristics of object-oriented programming

       The difference between object-oriented and process-oriented:

1) Process-oriented programming

  • Program = data structure + algorithm
  • Separate data and data processing processes that are essentially closely related and interdependent in objective things. Process-oriented programming is algorithm design based on data structures.
  • This substantial dependence and formal separation makes large programs not only difficult to write, but also difficult to debug, modify, and maintain. When the data structure changes, all or part of its related processing needs to be modified, resulting in poor code reusability. .

2) Object-oriented programming

  • Object = data structure + algorithm
    Program = (object + object +... + object) + message
  • A programming method based on objects and using events or messages to drive objects to perform corresponding processing.
  • Encapsulate data and operations on data together as an interdependent and inseparable whole - an object.
  • Using data abstraction and information hiding technology, this whole thing is abstracted into a new data type - class. The higher the integration level of a class, the more suitable it is for the development of large programs.
  • Object-oriented describes the system in a data-centered rather than a function-centered manner, because data is more stable than functions.

                                                   Process-oriented programming approach VS Object-oriented programming approach

Insert image description here
       Object-oriented programming includes two aspects:
       ① Designing the various classes required, that is, deciding which data and operations to encapsulate together.
       ②Consider how to send messages to the object (call the member function of the object) to achieve the required operations. At this time, the design program is like a master scheduler, constantly sending messages (commands) to each object to make these objects active (activate these objects) and complete their respective scope of responsibilities.
注:类是C++中十分重要的概念,它是实现面向对象程序设计的基础。类是所有面向对象的语言的共同特征,所有面向对象的语言都提供了这种类型。一个有一定规模的C++程序是由许多类构成的。C++支持面向过程的程序设计,也支持基于对象和面向对象的程序设计。基于对象就是基于类,基于对象的程序是以类和对象为基础的,程序的操作是围绕对象进行的。在此基础上利用继承机制和多态性,就成为面向对象的程序设计。把一组数据和相关的操作放在一起,这就是面向对象程序设计中的对象。

3. Object-oriented software development

  1. Object-oriented analysis
           Object-oriented analysis should follow object-oriented concepts and methods. In the analysis of tasks, the relevant objects (the properties and behaviors of objects) and the connections between objects should be summarized from objective things and the relationships between things. And objects with the same properties and behaviors are represented by a class.
  2. Object-oriented design
           conducts specific design for each part based on the demand model formed during the object-oriented analysis stage. The first step is to design the class. The design of the class may include multiple levels (using inheritance and derivation mechanisms). Then based on these classes, programming ideas and methods are proposed, including the design of algorithms. At this stage of the design, no specific computer language is involved.
  3. Object-oriented programming
           uses a computer language to write a program based on the results of object-oriented design.
  4. Object-oriented testing
           Object-oriented testing uses classes as the basic unit of testing to implement testing using object-oriented methods.
  5. Object-oriented maintenance
           During the use of any software product, users may need to improve the performance of the software, which requires modifying the program. Maintenance procedures are facilitated due to the object-oriented approach. Because of the encapsulation of classes, modifying one class has little impact on other classes (non-subclasses), greatly improving the efficiency of program maintenance.

2. Class declaration and object definition

       In object-oriented programming, a large number of objects are used, and programmers are required to analyze the problem and abstract the concept of class. When designing the program, the class type must first be declared, and then the class type variable, that is, the object.

1. The relationship between classes and objects

       Classes represent the commonalities and characteristics of a certain group of objects. An object is a variable of class type. Classes are abstract and do not occupy memory space. Objects are specific and take up memory space.

2. Declare class type

       A class is a type that needs to be defined by the user. If a class type is to be used in the program, the programmer must declare it as needed, or he can use a class that has been designed by others. Declaring a class type is similar to declaring a structure type.

结构体声明:
struct  student
	{
    
    
	     int    num;
	 	 char  name[20];
	 	 char  sex; 
	};
student  st1,st2;
类声明:
class  student
{
    
    
     int   num;
 	 string  name;
 	 char sex;
 	 void  setdata()
 	{
    
    	cin >> num;
 		cin >> name;
 		cin >> sex;
 	}
 	void display()
 	{
    
    	cout<< num<<endl;
 		cout<< name<<endl;
 		cout<< sex <<endl;
 	}
 };
student   st1,st2;

The format of C++ class definition.
Insert image description here
The access attributes of a class are: public, private and protected.

Access control Attributes
public (public member) The external interface of a class can be accessed by member functions of this class and other functions within the scope of the class.
private (private member) Only member functions of this class are allowed to be accessed, and no access is allowed outside the class (except friends).
protected (protected members) Only member functions of this class and derived classes are allowed to be accessed.

注:在定义类时,这三类成员不分前后顺序,也可以重复出现。一般推荐最多出现一次。

3. Define methods of objects

  1. Declare the class type first and then define the object.
    class class name object name table
    class student st1, st2;
    class name object name table
    student st1, st2;
  2. Objects are defined at the same time as the class type is declared.
    class class name
    { private: public: } object name list;




  3. The class name does not appear and the object is defined directly (although this method is legal in C++, its use is not recommended.)
    class
    { private: ... public: ... } object name table;




4. The difference between class and structure types

       If a class declared with class does not have member access qualifiers, all members are limited to private by default;
       if a class declared with struct does not have member access qualifiers, all members are limited to public by default.
Insert image description here

3. Member functions of classes

       When declaring a class, you must define functions that access the data members of the class, called member functions of the class.

  1. Properties of Member Functions
            A class member function is a type of function that can access all members of this class. The general method is to specify the member functions that need to communicate with the outside world as public, as the interface between the class and the outside world.
  2. The format of defining a member function outside the class
            : type class name::function name (formal parameter list)
                      {member declaration}
class  student
{
    
    
	      int   num;
	 	  string  name;
	 	  char sex;
	      public:  
			void   setdata();
	 		void  display();
};
void  student :: setdata()
	 	{
    
    	cin >> num;
	 		cin >> name;
	 		cin >> sex;
	 	}
void student :: display()
	 	{
    
    	cout<< num<<endl;
	 		cout<< name<<endl;
	 		cout<< sex <<endl;
	 	}  
student st1,st2;

注:(1)在类外定义成员函数时,必须在函数中增加类名,用于限定它属于哪个类,::是作用域限定符或称作用域运算符。上面的例子中如果函数不用成员访问限定符,函数就成了全局作用域中的display函数而不是成员函数。(2)如果在::前不带类名,或函数名前既无类名又无作用域运算符::,表示该函数是全局函数。(3)类的实现内容通常较大,为了便于阅读、管理和维护,最好将一个类拆分成一个.cpp文件和一个.h文件。

  1. Built-in functions
           C++ defaults to member functions defined within a class as inline functions. If a member function is defined outside the class, the system does not treat it as an inline member function by default. In this case, the inline keyword must be added before the function when declaring it.
class  student
{
    
    
    int   num;
	string  name;
	char sex;
	public:  
	inline  void   setdata()
	inline  void   display()
};
  1. The storage method of member functions.
           When objects are defined by classes, the system allocates memory space for each object. The member functions of objects of the same class are the same. If each object member function allocates memory space, it will cause a lot of waste. The way C++ handles this is to allocate memory space only for the data members of the object, and all objects of a class share a member function space.
    Insert image description here

4. References to object members

       After the object is defined, the public members in the object can be directly accessed in the program. They can be data members or member functions. There are three ways to access object members in a program:

  1. Use object name and member operator to access members.
    Format: object name. member name.
    Example: st1.display(); // Call member function
           display(); // Call ordinary function.

注:只有成员函数可以访问类中的所有成员,而在类外只能访问公有成员。

  1. Accessing members using pointers to objects
class Time
 {
    
    
     public:
  	 int hour;
 	 int minute;
 };
Time  t, *p; 
p= &t;
cout<< p->hour<<endl;

注·:p->hour表示p当前指向对象t中的成员hour, 此时(*p).hour也代表对象t中的成员hour,在这个例子中,p->hour、(*p).hour、t.hour三种表示是一个意思。

  1. Access members using object references.
           If you define a reference B for an object A, B is an alias of object A. A and B are both objects, so you can access members of the object by reference.
           Example: Time t1;
                  Time & t2=t1;
                  cout<< t2.hour;
           Here t2 is the alias of t1, so accessing t2.hour is accessing t1.hour.

注:类的成员可以是其他类的对象,但不能以类自身的对象作为本类的成员,而类自身的指针和引用可以作为类的成员。

5. Simple application of classes and objects

Example 1: Output time (hour: minute: second)

#include <iostream>
using namespace std;
class Time
{
    
      public:
	  int hour;
	  int minute;
	  int sec;
};
//第一种
int main()
{
    
      
    Time t1;
    cin>>t1.hour >>t1.minute>>t1.sec;       
    cout<<t1.hour<<":"<<t1.minute<<":"<<t1.sec<<endl;
    Time t2;
    cin>>t2.hour>>t2.minute>>t2.sec;
    cout<<t2.hour<<":"<<t2.minute<<":"<<t2.sec<<endl;
    return 0;
}
//第二种
int main()
{
    
    
	 void set_time( Time& ) ;  //  使用引用形参
	 void show_time( Time& );
	 Time t1;
	 set_time(t1);
	 show_time(t1);
	 Time t2;
	 set_time(t2);
	 show_time(t2);
	 return 0;
} 
void set_time(Time& t)
{
    
    
	 cin>>t.hour;
	 cin>>t.minute;
	 cin>>t.sec;
}	 
void show_time(Time& t)
{
    
    
	  cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;
} 
//第三种
#include <iostream>
using namespace std;
class Time
{
    
    
    public:
	   	void set_time() ;
	  	void show_time();
	private:
	   	int hour;
	   	int minute;
	   	int sec;
};
int main()
{
    
    
  	Time t1;
  	t1.set_time();
  	t1.show_time();
  	Time t2;
  	t2.set_time();
  	t2.show_time();
  	return 0;
 }
void Time::set_time()
{
    
    
	cin>>hour;
	cin>>minute;
	cin>>sec;
}	 
void Time::show_time()
{
    
    
	cout<<hour<<":"<<minute<<":"<<sec<<endl;
}

Example 2: Find the maximum value in an integer array

#include <iostream>
using namespace std;
class Array_max
{
    
    
    public:
   	void set_value();
   	void max_value();
   	void show_value();
    private:
   	int array[10];
   	int max;
};
void Array_max::set_value()
{
    
     	int i;
	for (i=0;i<10;i++)
	cin>>array[i];
}
void Array_max::max_value()
{
    
    	int i;
	max=array[0];
	for (i=1;i<10;i++)
	if(array[i]>max) max=array[i];
}
void Array_max::show_value()
{
    
    	
   cout<<"max="<<max;
}
int main()
 {
    
    	
    Array_max  arrmax;
  	arrmax.set_value();
  	arrmax.max_value();
  	arrmax.show_value();
  	return 0;
 }

Insert image description here

6. Class closure and information concealment

1. Realize the separation of public interfaces and private interfaces

       C++ achieves encapsulation through classes. The function of classes is to encapsulate data and algorithms for operating data in class types. When declaring a class, data members are generally designated as private to isolate them from the outside world, and member functions that are called by the outside world are designated as public. The outside world can access the data members through public functions. The only connection between the outside world and the object is to call public member functions. Public member functions are the public interface of a class used by users. Users can call public member functions to implement certain functions. Users only need to understand the functions of each public member function and do not need to understand how these functions are implemented. This is the separation of interface and implementation.
       In order to prevent users from arbitrarily modifying public member functions and thus changing operations on data, users are often not allowed to see the source code of public member functions. The data in the class is private, and the details of implementing data operations are hidden from users. This implementation is called a private implementation. The separation of the public interface and private implementation of this class results in information hiding.
       The advantages of information hiding are:
       (1) If you want to modify or expand the functions of a class, you only need to modify the relevant data members and member functions in the class, and the parts outside the class do not need to be modified. When the interface is separated from the implementation (operations on data), as long as the interface of the class does not change, changes to the private implementation will not affect other parts of the program.
       (2) If errors in reading and writing data in a class are found during compilation, there is no need to check the entire program, only the member functions in this class that access these data. This makes the design, modification and debugging of programs (especially large programs) convenient and simple.

2. Separation of class declaration and member function definition

       When developing object-oriented programs, the declaration of the class (including the declaration of member functions) is generally placed in the specified header file, and the relevant header files only need to be included in the program. There is no need to repeat class declarations in the program. Another method is to not define the class member functions in the header file, but to put them in a separate file.
Insert image description here
Insert image description here
       In practice, several commonly used class declarations with similar functions are gathered together to form a class library. Class libraries include standard class libraries provided by the C++ compilation system and user class libraries.
The class library has two components:
       (1) Class declaration header file
       (2) Compiled member function definition, which is the object file.
       Users can use these classes and their member functions as long as they load the class library into the subdirectory of the C++ compilation system and use the include command to include the header file of the class declaration into the program.

Guess you like

Origin blog.csdn.net/weixin_43312470/article/details/108045896