C++ programming [Tan Haoqiang] Part 3: Object-based programming

table of Contents

Chapter 8 Classes and Objects

Overview of object-oriented methods

Class declaration and object definition

Reference to object member

Class encapsulation and information concealment

Chapter 9 Further Discussion on Classes and Objects

Constructor

Destructor

Object array

Object pointer

Protection of shared data

Dynamic creation and release of objects

Assignment and copying of objects

Static member

Tomomoto

Class template

Chapter 10 Operator Overloading

What is operator overload

Methods and rules of operator overloading

Operator overloaded functions as class member functions and friend functions

Overloaded Binary Operator

Overloaded unary operator

Overload stream insertion operator and stream extraction operator

Conversion between different types of data

Type conversion with type conversion function


Chapter 8 Classes and Objects

Overview of object-oriented methods

Process-oriented: suitable for relatively small-scale programs, in fact, it is oriented to realize each function one by one, program = algorithm + data structure

Object-oriented: suitable for relatively large-scale programs, oriented to objects encapsulated by data and functions, program = multiple objects + messages [object = algorithm + data structure]

Object: Any specific things in the external world can be seen as a specific object in C ++, object consists of data and function composition

Attributes: the static characteristics of the object, such as the number of students in the class and the classroom

Behavior: the dynamic characteristics of the object, such as a class meeting, etc. The behavior is controlled by the message

Encapsulation: One is to encapsulate data and code in an object, and the other is to hide some parts of the object from the outside

Abstraction: A class is an abstraction of an object, a class is a template of an object, an object is a special case of a class, or an object is a concrete manifestation of a class

Inheritance and reuse: Inheritance is the ability to use the previous class to expand some functions to generate a new class, reuse is software reuse

Polymorphism: Send the same message to different objects, and they perform different actions respectively called polymorphism

Class declaration and object definition

Classes are abstract and do not occupy memory, while objects are specific and occupy memory. In fact, a class is a data structure in a broad sense.

The declaration method of the class is also developed from the structure type. In C++, the two can even be used in common. The difference is that the class defaults to private when it is not specified, and the structure defaults to public, but try to use class to create the class, private and public is the member access qualifier

The class encapsulates the data and the operation. Generally speaking, the class hides the data and uses the member function as the external interface

Precautions for using class functions: pay attention to the calling permissions, pay attention to the scope of the function (what range of data and functions it can call)

The member function in public is the external interface of the class, the member function in private is the utility function of other members in the class, and users outside the class cannot call

Member functions can also be defined outside the class, for example:

class Student
{
    public:
        void display();
    private:
        int num;
        string name;
        char sex;
};

void Student::display()
{
    cout<<num<<endl;
    cout<<name<<endl;
    cout<<sex<<endl;
}

Student stu1, stu2;

Pay attention to how the above member function is defined-void Student::display(), where the two colons :: represent that this function belongs to the class member of the class before the two colons. If there are only these two colons, Or nothing, then this function is not a member function, but a global function

The space occupied by an object is only related to the space occupied by the data members of the object, and has nothing to do with member functions, which means that the space for storing functions in the class is saved

Reference to object member

Three ways to reference members in a class

(1) Object name. Member name

stu.num

(2) Use pointers:

pStu->num     //方式一
(*pStu).num   //方式二

(3) Use reference: stu2 is an alias of stu1, they both refer to the same piece of memory

Student stu1;
Studnet &stu2 = stu1;

For C++, as long as the class is well defined, the work of writing a program is very, very simple

Class encapsulation and information concealment

The role of the class is to encapsulate data and algorithms in the abstract data types declared by the user. The user mainly implements the functions provided by the class by calling public member functions (such as assigning values ​​to data members, displaying the values ​​of data members, and processing data). Wait)

Separation of public interface and private implementation: For example, in the process of software development, the separation of the two must be realized. In this way, as long as the interface of the class does not change, the change to the private implementation will not affect other parts of the program

If a class of knowledge is used by a program, then the declaration of the class and the definition of member functions can be written directly at the beginning of the program, but if the class is used by multiple programs, the amount of such repetitive work is too great. Generally, in object-oriented development, the common practice is to put the class declaration (including the declaration of member functions) in the header file. If the user wants to use this class, then just wrap this header file in. At the same time, for information concealment, the class member functions are generally not placed in the header file, but are placed in a separate inquiry.

An example of the separation of class declaration and member function definition [three files in total]:

File 1: Class declaration in the header file:

//文件名:student.h
//这是个类声明头文件
#pragma once          
#include <string>
using namespace std;

class Student          //类声明
{
public:
	void display();   //公用成员函数声明
private:
	int num;
	string name;
	char sex;
};

File 2: The definition of class member functions

//文件名:student.cpp
#include <iostream>
#include "student.h"         //注意包含这个类声明头文件
using namespace std;
 //在本文件中进行函数的定义
void Student::display()      //注意这里的两个冒号很重要
{
	cout << num << endl;
	cout << name << endl;
	cout << sex << endl;
}

File 3: Main function

//文件名:main.cpp
#include <iostream>
#include "student.h"    //包含这个类声明头文件
using namespace std;

int main()
{
	Student stu;        //定义一个对象
	stu.display();      //执行对象的display函数,这里你点那个点就会发现其它的成员都访问不了
	return 0;
}

Who is it for? stu

Who is the method? display()

Who is the news? stu.display()

 

Chapter 9 Further Discussion on Classes and Objects

Constructor

Simply put, the constructor is to handle the initialization of the object. It should be noted that the data members of the class cannot be initialized when the class is declared, because the class is just a data type, not a real object.

Examples of constructors:

#include <iostream>
using namespace std;
class Time
{
public:
	Time()  //定义构造成员函数,函数名与类名相同,通过构造函数对对象中的数据成员赋初值
	{
		hour = 0;
		minute = 0;
		sec = 0;
	}
	void set_time();
	void show_time();
private:
	int hour;
	int minute;
	int sec;
};

//定义成员函数用于赋值
void Time::set_time()
{
	cin >> hour;
	cin >> minute;
	cin >> sec;
}

//定义成员函数用于输出
void Time::show_time()
{
	cout << hour << ':' << minute << ':' << sec;
}

//主函数
int main()
{
	Time t;        //建立对象t,同时调用构造函数t.Time()进行对象初始化
	//t.set_time();
	t.show_time();
	return 0;
}

In addition, the parameter initialization table can be used to initialize the data members

Constructor overloading: Multiple constructors can be defined in a class to provide different initialization options for class objects. These constructors have the same name, but the number of parameters or the types of parameters are different, which is called Constructor overload, but a class has only one default constructor

Destructor

There is a ~ symbol in front of the destructor. Its function is the opposite of that of the constructor. The function of the destructor is not to delete the object, but to complete some clean-up work before the object takes up memory. A class can have many constructors (overloading), but only one destructor. Constructed first and then destructed, constructed later, destructed first, similar to a stack

Object array

Arrays can be composed not only of simple variables, but also objects

Object pointer

The first address of the space occupied by the object is the pointer of the object

(1) Pointer to the data member in the object

The definition method is the same as the structure

(2) Pointers to function members in the object

Pointer variables of ordinary functions: void (* p) (); where p is a pointer variable that points to void type functions

Pointer variable pointing to the object member function: void (Time:: * p)( ); where p is the pointer variable pointing to the public member function of the Time class

How to define it? Example: p = &Time::get_time; Note that the get_time here is just the function name, without parentheses

Protection of shared data

To ensure that the data can be shared within a certain range, but also to ensure that it is not arbitrarily modified, then you can use const to define the relevant data as a constant

Dynamic creation and release of objects

Examples of dynamically creating and releasing objects: [similar to malloc() and free()]

Box * pt;      //定义一个 Box * 类型的指针变量 pt
pt = new Box;  //在 pt 中存放新建的对象的首地址
delete pt;     //释放 pt 所指向的内存空间

Assignment and copying of objects

Copy = New + Assign

Static member

Static data member

If you want a certain data member in each object to be consistent, then you can define it in the class as follows:

static int height;

Static member function

Similar to static data members

static float sum();

Tomomoto

Friend is something between public and private. If there is a function defined outside of this class (it can be a non-member function or a member function of other classes), then use friend to declare this function in the class body. This function is called a friend function of this class. This friend function can access the private members of this class.

For example:

#include <iostream>
using namespace std;
class Time
{
public:
	Time(int,int,int);
	friend void display(Time &);   //声明display为Time类的友元函数
private:
	int hour;
	int minute;
	int sec;
};

//定义构造函数用于赋初值
Time::Time(int h,int m,int s)
{
	hour = h;
	minute = m;
	sec = s;
}

//定义成员函数用于输出
void display(Time & t)  //t是Time类对象的引用,这个函数是友元函数
{
	cout << t.hour << ':' << t.minute << ':' << t.sec;
}

//主函数
int main()
{
	Time t(10,13,20);  
	display(t);   //t是Time类对象
	return 0;
}

Class template

Examples of using class templates:

#include <iostream>
using namespace std;
template <class numtype>
class Compare
{
public:
	Compare(numtype a, numtype b)
	{
		x = a;
		y = b;
	}
	numtype max()
	{
		return(x > y) ? x : y;
	}
	numtype min()
	{
		return(x < y) ? x : y;
	}
private:
	numtype x, y;
};

int main()
{
	Compare <int> cmp_1(3, 7);
	cout << cmp_1.max() << " is the max of two numbers" << endl;
	Compare <float> cmp_2(45.6, 98.7);
	cout << cmp_2.min() << " is the min of two numbers" << endl;
	return 0;
}

 

Chapter 10 Operator Overloading

What is operator overload

The so-called overloading is to give a new meaning. Function overloading is a multi-purpose function, the same function name can be used to represent functions of different functions; operator overloading is actually used all the time (for example, we use + to perform operations on integers, floating-point numbers, etc., in fact, this is operator overloading)

The so-called operator overloading is to give operators new meaning

Methods and rules of operator overloading

 

Operator overloaded functions as class member functions and friend functions

 

Overloaded Binary Operator

 

Overloaded unary operator

 

Overload stream insertion operator and stream extraction operator

 

Conversion between different types of data

 

Type conversion with type conversion function

 

Guess you like

Origin blog.csdn.net/weixin_43450646/article/details/106996297