C++ object-oriented design and use

Object Oriented Programming (OOP)

Object Oriented (Object Oriented) is a method of understanding affairs, an object-centric way of thinking

Object-oriented programming:

Object=(algorithm+data structure)
program=object+object+……+object

Object-oriented programming simulates the methods of understanding and processing things in nature, putting data and operating methods on data together to form a relatively independent whole—object. Similar objects can also abstract commonalities and form classes. ). The data in a class can usually only be processed through the methods provided by this class, and these methods become the interface between the class and the outside. The objects communicate through messages.

We call the information conveyed by the interaction between objects as messages.

C++ treats "sending a message to an object" into "calling a certain member function of the object"

Basic concept-object

All things in the world can be called Objects. The object can be tangible, such as a television set, etc. It can also be intangible, such as an account, a record, etc.

An object is an independent objective thing, which consists of a set of attributes and a set of operations that operate on the attributes.

  • Properties are the description of the static characteristics of the object
  • Operation is the description of the dynamic characteristics of the object

Attributes and operations are the two major elements of an object. For example, the attributes of the TV are: brand, size, weight, etc. Operations include: viewing, channel selection, volume adjustment, etc.

Basic concept-class

A class is an abstract concept used to describe the essential properties and class behaviors shared by a certain class of objects.

Simulated reality summarizes and divides objective things according to abstract principles.
Insert picture description here

The basic characteristics of object-oriented

  • abstract
  • Encapsulation and data hiding (a brief introduction)
  • inherit
  • Polymorphism

Encapsulation and data hiding

Encapsulation refers to combining the attributes and operations of an object to form an independent object in accordance with the principle of information shielding.

By restricting access rights to attributes and operations, the attributes can be "hidden" inside the object, and a certain interface can be provided to the outside. Only the interface can be operated on the object outside the object.

The encapsulation increases the independence of the object, thereby ensuring the reliability of the data.

External objects cannot directly manipulate the properties of the object, but can only use the services provided by the object.

Abstract design ideas

Data abstraction into attributes

The processing process is abstracted into operations (methods)
-For example: when building a library management system, instinctively know that there must be objects such as librarians/readers/books in the system, and the behavior of readers includes borrowing/returning books, Students also have their corresponding student ID/name/class, etc.

Class definition

C++ supports encapsulation and data hiding by establishing data types-classes. A well-defined class can be used as an independent module.

The definition format of the class is divided into a description part and an implementation part
-the description part contains data members and member function descriptions
-the implementation part is used to define member functions

The general definition format of a class is as follows:

class  <类名>
{
    
    
	public :
		<公有数据成员和成员函数>;
	protected:
        <保护数据成员和成员函数>;
	private :
        <私有数据成员和成员函数>;
};

classThe key to define the class is the data type specifier, <class name> is an identifier, used to uniquely identify a class (new data type), the part of the curly braces after the class name is the class body (Class Body ).

The class body defines the class member list (Class Member List)-data
member (Data Member)
-function (Member Function)

public, protected, and private are access specifiers

Generally, the public members are first explained in the class body, they are what the user cares about, and then private members are explained later. They are not of interest to the user, but this order is not necessary.

***note:

① A semicolon ";" must be added after the description of the class.

②The definition of the class is placed in a header file (.h) for other files that need to use the class to include

③The implementation part of the class is placed in a source file (.cpp), which needs to include the header file that defines the class

④ The definition and implementation of the class can be placed in one file, but it is not recommended, because the structure is not clear, which affects the readability of the program

Data member (attribute)

The types of data members in a class can be arbitrary, and various types of variables, pointers, arrays, etc. can be defined, and even objects of other classes.

When describing data members, generally according to the type and size of the data member, from small to large, this can improve the space utilization.

Only data members can be declared in the class definition, and the data members defined are not allowed to be initialized.

The data members of the class can only be declared in the class, and the data members of the class are preferably private

The external function needs to modify it, and generally only provides it with a public function interface, allowing it to access the private data of the class through the public member function of the class. Data members can also be placed in the public part, but it is not recommended

Member function (method)

Member functions can directly use any member in the class definition, can process data members, and can also call member functions.

The member function definition of a class can usually take two ways, namely external definition and internal definition (not recommended! It affects the readability of the program).

The implementation of member functions is generally placed outside the class, and the prototype of the function is declared in the class

When the implementation of a member function is outside the definition of a class, it must be declared, and the class name and the scope operator "::" are added before the function name to indicate which class a member function belongs to. The definition format is as follows:

返回类型  类名::成员函数名(参数说明)
{
    
    
	函数体 
}

The implementation of class member functions can also be placed in the class without adding the class name and scope operator

Access control

Three access specifiers: public, private and protected

Role: control access to members of the class

In the class defined by class, the default access method is private

In the definition of the class, all three access specifiers can be used multiple times (not recommended). Their scope is from the appearance of the specifier to the end before the next specifier or the end of the class body.

Visitor description

private: Private members of a class can only be accessed by member functions, friend functions, and friend classes of the class, and cannot be accessed outside the class

protected: The protected members of the class can be accessed by the member functions, friend functions, friend classes and derived class member functions of the class

public: The public members of the class can be directly accessed by the member functions, friend functions, and all external program codes of the friend class that can access the objects of the class. This part is often some operations (ie member functions)

The public members of the class are the external interface of the class

Class function

The class defines access control properties for functions (methods) and data (attributes)
—which members can be directly accessed by the outside world
—which members can only be accessed by their own member functions

Encapsulation and information hiding technology make the class very safe

Private data members can only be accessed by the class's own member functions

As long as the member function operation is reasonable and legal, the object is safe

Improve the maintainability of the program

Definition of object

Objects are instances of classes. The object belongs to a known class.

Before defining an object, you must first define the object's class.

The defined class can be used as a new data type

The syntax of the declaration: 类的名称 对象的名称;
For example:

例如:
Stack oneStack;		//Stack类型的对象
Stack arrayOfStack[10]; //Stack类型的对象数组
Stack *pStack=&oneStack;	//Stack类型的指针
Stack &s = oneStack;  // 引用一个Stack对象

Constructor

For the initialization of the object, the constructor is used. Write one or a set of constructors. Constructor is a special member function

The function of the constructor: allocate space for the object; assign initial values ​​to data members; request other resources.

How to declare a constructor:
—The function name and the class name are exactly the same
— the type of the constructor (return type) cannot be defined, and void
— the constructor should be declared as a public function, but it cannot be explicitly called like other member functions
—Constructor can have any type and any number of parameters, and a class can have multiple constructors (overloading)

When creating an object of a class, the constructor of the class is automatically called

Only one constructor is called when an object is created (according to the parameter list) and only once when it is created

Types of constructor

Ordinary constructor: a constructor with two or more parameters

Default constructor

Copy (copy) constructor

Type conversion constructor

Overloaded constructor

When a class needs to accept different initialization values, it is necessary to write multiple constructors, which constitute an overload relationship.

Example:

class Student{
    
    
private:
	char m_No[4],m_Name[21];
	int m_Age,m_Score[5];
public:
	Student();	//默认构造函数
	Student(char *name,int age,int score[5]);   //重载构造函数
};

Default constructor

  • Which constructor is the default constructor?

    A constructor with no parameters or all parameters have default values.

  • Is there a default constructor in the class?

    If no constructor is declared in the class, the compiler will automatically generate a public default parameterless constructor; if there is a constructor declaration, then the compiler will not generate a default constructor

  • When is the default constructor called?

    When the object is not specified to be initialized, the object is initialized according to the default constructor.
    For example: Person p1, p2; //Use the default constructor to initialize p1 and p2

  • There can only be one default constructor in a class
    (if all parameters of a constructor have default values, then it is meaningless to define a default constructor without parameters, which will cause ambiguity when calling)

Use default parameters in the constructor

You can specify the default values ​​of the parameters for the member functions of the class, including the constructor.

To put the default parameter value in the function declaration, not in the function definition

If all the parameters of a constructor have default values, then it is meaningless to define a default constructor without parameters, which will cause ambiguity when calling.

Example:

class CCube{
    
    
public:
	CCube(double len);
	CCube(int len=12);
	//CCube();
private:
	double m_len;
};
CCube::CCube(int len){
    
    m_len=len;}

Copy (copy) constructor

Special constructor

Function: Use an existing object to initialize a new object of this class

Declaration: There is only one parameter and the parameter is a reference to this type of object

class 类名{
    
    
	public:	类名(类名  &对象名);
	};

If the copy constructor is not specified in the class, the system automatically generates a default copy constructor as a public member of the class.

Shallow copy and deep copy
Shallow copy: simply copy the value of the object data member
Deep copy: not only copy the value of the object data member, but also generate new space for the pointer data member, and then copy the corresponding value

Examples:

#include <string.h>
#include <iostream.h>
class Employee
{
    
    
public:
	Employee(char *n);
	Employee(Employee &emp);
	~Employee();
public:
   char *name;
};
Employee::~Employee()
{
    
    //析构函数
	delete [] name;
}
Employee::Employee(char *n)
{
    
    
	name = new char[strlen(n)+1];
	strcpy(name,n);
}
Employee::Employee(Employee &emp)
{
    
    
	int len=strlen(emp.name);
	name=new char[len+1];
	strcpy(name,emp.name);
}
int main()
{
    
    
	Employee emp1("zhang");
	Employee emp2(emp1);
	//Employee emp2=emp1;
	cout<<"emp2.name = "<<emp2.name<<endl;
	return 0;
}

**Note: When the object contains dynamically allocated data members, the implementation of the copy constructor cannot just be a simple assignment. You should allocate new space for the data members of the current object, and then copy the corresponding data in the parameter object.

Other functions of the copy constructor

When the formal parameter of the function is the object of the class, when calling the function, it is used when the formal parameter is combined. At this time, create a new local object in memory and copy the actual parameters to the new object. Of course the copy constructor is also called.

When the return value of the function is a class object, it is used when the function execution completes and returns to the caller. The reason is to create a temporary object, and then return to the caller. Why not just use the local object to be returned? Because the local object dies when it leaves the function that created it, it is impossible to survive after returning to the calling function, so when dealing with this situation, the compiler system will create an unnamed temporary object in the expression of the calling function. This temporary The life cycle of an object is only in the expression at the function call. The so-called return object is actually calling the copy constructor to copy the value of the object into a temporary object. If the variable is returned, the processing is similar, except that the constructor is not called.

Conversion constructor

Provides a constructor with a single parameter

It is equivalent to converting a value or variable of another type into data of its own type.

It is very dangerous that the constructor of a class has only one parameter, because the compiler can use this constructor to implicitly convert the type of the parameter to the class type

Examples:

#include <string.h>
#include <iostream.h>
class CCube
{
    
    
public:
	CCube(double len)
	{
    
    
		m_len=len;
	}
public:
	double m_len;
};
int main()
{
    
    
	CCube cube=12.4;
	cube=11;    //隐式转换
	cout<<"cube.m_len = "<<cube.m_len<<endl;
	return 0;
}

执行结果:
cube.m_len = 11

explicit keyword

Keywords used only for the constructor of the class.

The compiler will not use the constructor declared as explicit for implicit conversion, it can only display and create objects in the program code

#include <string.h>
#include <iostream.h>
class CCube
{
    
    
public:
	explicit CCube(double len)
	{
    
    
		m_len=len;
	}
private:
	double m_len;
};
int main()
{
    
    
	CCube cube = 12.4;//不允许
	//cube=11;//不允许
	return 0;
}

Destructor

Special member function

Role: Do cleanup work before revoking the object, generally to release the space dynamically applied for during the life of the object

When the object exceeds its defined scope (that is, when the object is released), the compiler automatically calls the destructor.
-The object is defined in the function body, when the function ends, the destructor of the object is automatically called.
-The object is dynamically created using the new operator, when the delete operator is used to release it, delete will automatically call the destructor

The function name is similar to the class name (with a character "~" in front)

Note: The destructor has no return type, no parameters, and the destructor cannot be overloaded

If no destructor is defined, the compiler will automatically generate a default destructor with the following format:

类名::~默认析构函数名( )
{
    
    
}

The default destructor is an empty function.

Example:

class Student
{
    
    
public:
	 Student();
	~Student();
private:
	char *m_name;
};
Student :: Student()
{
    
    
	cout<<"Default constructor called"<<endl;
	m_name=new char[5];
	strcpy(m_name,"abc");
}
Student ::~Student()
{
    
    
	cout<<"Free"<<endl;
	delete []char;
}

Guess you like

Origin blog.csdn.net/qq_46485161/article/details/115315916