Overview of Chapter 1 of data structure C + + language description

Keywords: C++ data structure

1, Overview

  1. We regard each data structure as an abstract data type. It not only defines the organization of data, but also gives the operations to process data. In C + + language, classes are used to represent abstract data types, and objects are used to store and process data in specific applications.

  2. The creation of C + + classes is the basis for us to learn data structures. Inheritance and polymorphism expand the ability of object-oriented programming, so that it can be used to develop large-scale software systems based on class libraries.

  3. The first chapter is mainly familiar with the concept

1.1 abstract data type (ADT)

  1. Data abstraction is called abstract data type. It defines the data value range, representation structure and operation set of data.
  2. ADT gives a user-defined data type whose operators indicate how the user operates on data.
  3. ADT has nothing to do with specific applications, which allows programmers to focus on the data and the ideal model of its operation.

Case:

  1. Purchase information procedures maintained by the company

    Data:

    Article numberCurrent inventoryUnit PricePurchase level
    -Modify inventory when goods are soldModify price during price adjustmentWhen the inventory is less than the purchase level, the purchase information is given

    Operation:

    UpdateStockLevel() 	//Modify inventory
    AdjustUnitPrice() 	//Pro-rata Rates 
    ReorderItem()		//Order information required
    
  2. Dice game program
    ADT: its data includes the number of dice rolled, the total number of dice rolled and the number of points of each dice;
    Operations include: rolling dice, returning the total number of dice rolled this time, and printing the number of points of each dice rolled.

    Data:

    operation

    Toss()			// Roll dice
    Total()			// Find the total number of dice
    DisplayToss()	// Print points
    

ADT description specification

Header consisting of ADT name, description of data type and operation list.

Action list:

operationdescribe
inputSpecifies the input value given by the user
preconditionIndicates the data that the operation must have before it can be executed
processRepresents the action completed by the operation
outputRepresents the value returned to the user after the operation
Postcondition (result)Represents any changes made within the data
initializeMost ADT s are initialized to assign initial values to data
Constructor (constructor)In C + + language environment, initialization operation is called constructor

To sum up, the ADT specification is described as follows:

	ADT ADT name is
		Data
			Describe the structure of the data
		Operations
			Constructor
				Initial values:		The data used to initialize the object
				Process:			Initialize object
			Operation 1
				Input:			User entered value
				Preconditions:	The state necessary for the data before the system performs this operation
				Process:		Action on data
				Output:			Data returned to the user
				Postconditions:	Status of data after system operation
			Operation 2
				......
			operation n
				......
		end ADT ADT name
ADT case
  1. The data of the abstract data type Dice includes: the number of Dice rolled each time, N, the total number of points rolled, and a table with n items to store the number of points rolled for each Dice.

    ADT Dice is
    Data
    	The number of dice rolled this time. It is an integer greater than or equal to 1.
    	The total number of points thrown this time. It is an integer. If you throw N Dice, the value is N And 6 N between.
    	The point table of each die rolled in this roll. Each value in the table is an integer from 1 to 6.
    Operations
    	Constructor
    		Initial values:	Number of dice rolled
    		Process:		Initialization data, given the number of dice rolled each time
    	Toss
    		Input:			nothing
    		Preconditions:	nothing
    		Process:		Roll the dice and count the total points
    		Output:			nothing
    		Postconditions:	The total number of dice rolled and the number of points per dice
    	Total
    		Input:			nothing
    		Preconditions:	nothing
    		Process:		Retrieve the data item of the total points of this throw
    		Output:			Return the total points of this throw
    		Postconditions:	nothing
    	DisplayToss
    		Input:			nothing
    		Preconditions:	nothing
    		Process:		Print the number of dice rolled this time
    		Output:			nothing
    		Postconditions:	nothing
    end ADT Dice
    
  2. Abstract data type of circle: radius (only radius is required for metering). Operations include: area and perimeter

	ADT Circle is 
		Data
			Nonnegative real number, give the radius of the circle
		Operations
			Constructor
			Initial valus:		Radius of circle
			Process:			Assign an initial value to the radius of the circle
		Area
			Input:				nothing
			Preconditions:		nothing
			Process:			Calculate the area of a circle
			Output:				Returns the area of a circle
			Postconditions:		nothing
		Circumference
			Input:				nothing
			Preconditions:		nothing
			Process:			Calculate the circumference of a circle
			Output:				Returns the circumference of a circle
			Postconditions:		nothing
	end ADT	Circle

1.2 C + + classes and abstract data types

  1. C + + language uses user-defined Class types to represent abstract data structures. A Class is composed of multiple members storing data values and "methods". Methods define methods to access data, and variables of type Class become objects.

  2. Class can be divided into two parts: public part. Users can use objects without knowing the internal details of objects; The private part consists of data and internal operations that help implement data abstraction. For example, the class of ADT circle contains a private data member - radius, and its public members include constructors and methods to calculate area and perimeter.

    Class:

	private:
		Data members:		Value 1			Value 2
		Internal operation

	public:
		Constructor
		Operation 1
		Operation 2

Circle class

	private:
		radius(Radius)
	
	public:
		Constructor(Constructor)
		Area((area)
		Circumference(Perimeter)

Data encapsulation and information hiding

  1. Class encapsulates information by wrapping data and methods together and treating them as a whole.
  2. Class hides application details in structure and strictly restricts external access to its data and operations. This feature is called information hiding, which protects the integrity of data.
  3. The class controls the access of external applications through private and public parts. The members of the private part are used internally by the methods inside the class, and the public members and methods can be used by users. Users can get private variables by calling public methods.

message passing

  1. In an application, the public members of an object can be called by an external program. This call control is completed by the main control module (main program or subroutine) interacting with each object. The control code commands the object to access data by some method or operation. This process of commanding the activity of each object is called * * message passing *.
  2. Information is passed along with messages as input and output data.

1.3 objects in C + + applications

  1. When declaring a C + + class, it is called class declaration when no member function is defined. It is a specific representation of ADT. The specific implementation of the method is in the class implementation independent of the declaration.

  2. Through the complete Circle class, this paper explains the implementation of C + + class and the application of object, and uses the program to calculate the wall cost of a circular pool.
    Requirements:

    Implementation procedure:

    #include<iostream>
    using namespace std;
    
    const float PI = 3.14152;
    const float FencePrice = 3.5;
    const float ConcretePrice = 0.5;
    
    class Circle;
    
    class Circle 
    {	
    	private:
    		float radius;
    	
    	public:
    		// Constructor
    		Circle(float r);
    		
    		// A function that calculates the circumference and area of a circle 
    		float Circumference(void) const; 
    		float Area(void) const;
    };
    
    //Class implementation
    //Constructor initializes the data member radius with a class
    Circle::Circle(float r):radius(r){}
    
    // Calculate the circumference of a circle
    float Circle::Circumference(void) const
    {
    	return 2 * PI * radius;
    }
    
    // Calculate the area of a circle
    float Circle::Area(void) const
    {
    	return radius * radius * PI;
    } 
    
    int main()
    {
    	float radius;
    	float FenceCost, ConcreteCost;
    	
    	// Set floating point number output to display only two digits after the decimal point
    	cout.setf(ios::fixed);
    	cout.setf(ios::showpoint);
    	cout.precision(2);
    	
    	// Prompt the user for radius
    	cout << "Enter the radius of the pool:";
    	cin >> radius;
    	
    	// Define a Circle object
    	Circle pool(radius) ;
    	Circle poolRim(radius + 3);
    	
    	// Calculate fence cost and output
    	FenceCost = poolRim.Circumference() * FencePrice;
    	cout << "Fencing Cost is $" << FenceCost << endl;
    	
    	// Calculate the aisle cost and output it
    	ConcreteCost = (poolRim.Area() - pool.Area()) * ConcretePrice;
    	cout << "Concrete Cost is $" << ConcreteCost << endl; 
    } 
    
    

    Operation results:

    Const qualifier: the qualified function member does not change the value of the data member, which is used in the declaration and definition of the function

1.4 object design

  1. From simple to complex classes, the class itself contains other classes. The class generated by this composite method can access the member functions of the class in the class. Object compliance expands data encapsulation and information hiding, and realizes code reuse
  2. Object oriented programming languages also support new classes derived from other classes by inheritance

Object and its reuse

Geometry is composed of point sets such as lines and rectangles. Points can be defined as an original object to describe lines and rectangles, and this case is used to illustrate objects and composites.

1. The point is a plane position, so we use coordinates( x, y)Represents the point object, x and y Represents the horizontal and vertical distances from the point to the origin, respectively.
2. Two points define a straight line, so P1  and P2 A point defines a line segment
3. A rectangle is an edge orthogonal quadrilateral. The upper left point and the lower right point determine a rectangle.

To sum up, the classes of point, Line and Rectangle are obtained:

	// Point class 
class Point
{
	private:
		float x, y;						// Horizontal and vertical positions of points 
		
	public:
		Point (float h, float v);		// Assign h to x and v to y 
		float GetX(void) const;			// Return x coordinate (horizontal position) 
		float GetY(void) const;			// Return y coordinate (vertical position) 
		void Draw(void) const;			// Draw a point at (x, y) 
};

// Line class 
class Line
{
	private:
		Point p1, p2;					// Two endpoints of a segment 
		
	public:
		Line(Point a, Point b);			// Assign a to P1 and B to P2 
		void Draw(void) const;
		
}; 

Objects and inheritance

Inheritance is an intuitive concept. For example, each of us inherits the race, skin color, eye color and other characteristics of our parents

Inheritance of zoology:

In the race chain, the subclass inherits all the attributes of the parent class. For example, the dog has the attributes of all mammals and also has the attributes of distinguishing the dog from the cat and elephant. The inheritance diagram of zoology can be explained as follows:

Scottish shepherd poodle "yes" dog
Dogs are mammals

In the chain, "mammal" is the accumulation of dogs, "dogs" are called derived classes, and subclasses can inherit attributes from parent and grandfather classes.

Inheritance in programming

For example: ordered list and inheritance

An ordered table is a special table whose elements are sorted in ascending order
As an abstract data type, ordered list saves most operations of normal sequence table (SeqList) except insertion. The insertion operation of ordered table must maintain the ascending order of the table.

The class OrderedList is derived from the class SeqList. It inherits many accumulated operations, but rewrites the Insert operation as inserting elements in an orderly order.

ADT:

	ADT OrderedList is 
		Data
			<with ADT SeqList>
		Operations
			Constructor		<Execute base class Constructor>
			ListSize		<with ADT SeqList>
			ListEmpty		<with ADT SeqList>
			ClearList		<with ADT SeqList>
			Find			<with ADT SeqList>
			Delete			<with ADT SeqList>
			DeleteFront		<with ADT SeqList>
			GetData			<with ADT SeqList>
		Insert
			Preconditions:	nothing
			Input:			The element to insert into the table
			Process:		Insert the element where it can be kept in order in the table
			Output:			nothing
			Postconditions: Add a new element to the table and increase its size by 1
	end ADT OrderedList

Software reuse

  1. Inheritance can realize code reuse, save software development time and improve the integrity between application and system
    For example, during system upgrade, in order to keep the application running, the original operating system can be defined as a base class, and the upgraded system can be run as a derived class with new functions.
Description of classes SeqList and OrderedList

The OrderedList class inherits the SeqList class

	SeqList class
	
	class SeqList
	{
		private:
			// The array storing the table and the number of current elements in the table
			DataType listitem[ARRAYSIZE];
			int size;
		public:
			// Constructor
			SeqList(void);
			// Methods of accessing tables
			int ListSize(void) const;
			int ListEmpty(void) const;
			int Find(DataType & item) const;
			DataType GetData(int pos) const;
			//How to modify a table
			void Insert(const DataType& item);
			void Delete(const DataType& item);
			DataType DeleteFront(void);
			void ClearList(void);
	};

There is the word const after the definitions of the functions ListSize, ListEmpty, Find and GetData. These functions are called constant functions
The word const appears in the parameter table of the functions Insert and Delete, which is expressed in C + + in this way: Although the parameter address is passed, the value of the parameter is not allowed to be modified
Syntax of C + + declaration of derived classes: in the header, the base class is represented by a colon (:) after the class name

	OrderedList class
	
	class OrderedList:public SeqList				// Inherit from class SeqList
	{
		public:
			OrderedList(void);						// Initialize the base class to create an empty table
			void Insert(const dataType& item);		// Insert elements into the table in order
	};

The function Insert overrides the function with the same name in the base class. It traverses the table inherited from the base class and inserts the elements in a position that can maintain their ascending order.

1.5 application of class inheritance

  1. Graphical user interface (GUI) has important applications in programming and database systems

    Graphic applications focus on objects such as windows, menus and dialog boxes. The most basic window is a data structure with data and operations suitable for all types of windows
    These operations include opening a window, creating or modifying a window title, creating a scroll bar and a drag area, etc
    Other windows such as dialog box, menu and text window can inherit these basic structures

As shown in the following figure, the classes Dialog and TextEdit are derived from the class Window

  1. Multiple inheritance: derived classes come from two or more base classes. For example, a word processor includes an Editor and a View used to display text in a window The Editor reads the character stream and changes the character stream by inserting and deleting the string and corresponding format information; the browser is responsible for displaying the text on the screen with the given font and window information, so that the Screen Editor can be defined as a derived class based on the classes Editor and View.

1.6 object oriented programming

1.7 program testing and maintenance

Object test

Control module test

Program maintenance and documentation

1.8 C + + programming language

1.9 abstract base class and polymorphism*

  1. Class inheritance is combined with abstract base classes, which provide a public interface independent of class data and user operations
  2. Although the internal implementation of the class changes, the original public interface remains unchanged
  3. The object-oriented language implements this function by defining the name of each public operation (public function) and the base class of parameters
  4. Abstract base classes provide only limited implementation details and focus on the definition of common operations
  5. C + + abstract base classes define some operations as pure virtual functions
  6. The keyword Virtual and assigning an operation to 0 represent pure Virtual functions
	template<class T>
	class List
	{
		protected:
			// The number of elements in the table is modified by the derived class
			int size;
			
		public:
			// Constructor
			List(void);
			
			// Methods of accessing tables
			virtual int ListSize(void) const;
			virtual int ListEmpty(void) const;
			virtual int Find(T& item) = 0;
		
			// How to modify a table
			virtual void Insert(const T& item) = 0;
			virtual void Delete(const T& item) = 0;
			virtual void ClearList(void) = 0; 
	}

Polymorphism and dynamic binding

C + + inheritance can be implemented in many ways:

  1. Implementation with virtual function of abstract base class
  2. Virtual functions can support inheritance by inheriting two or more objects in the family tree, defining functions with the same name but different tasks
Polymorphism: allows different objects to respond to the same message, which is determined dynamically when receiving information

Polymorphism cases:

2, Basic data type

3, Abstract data types and classes

4, Group class

5, Stack and queue

6, Abstract operation

7, Formal data type

8, Classes and dynamic storage

Posted by Joel.DNSVault on Tue, 30 Nov 2021 06:37:18 -0800