A comprehensive and detailed illustration of the C++ study notes class and object "encapsulation" and other knowledge summary

 

Foreword:

        This article is summarized by the author in the process of learning C++ classes and objects. Writing a blog is not only a reminder to myself, but also to share with more partners for learning and communication. If there are some loopholes or mistakes in this article, you are welcome to criticize and correct, and you are also welcome to make additions to exchange and learn together. This article has more than 7,600 words, and it is better to cooperate with the catalog. I believe it will be helpful to you. Not much to say, first look at the mind map below, which covers most of the content of this article, so that we have a better thinking framework. (As shown below)

Table of contents

 

Foreword:

1.1 The basic characteristics of object-oriented programming

1.1.1 Abstraction

 1.1.2 Packaging

1.1.3 Inheritance

 1.1.4 Polymorphism

 1.2 Classes and Objects

1.2.1 Class definition

1.2.2 Class Access Control

1.2.3 Objects

1.2.4 Member functions of classes

1. Member function implementation

2. Call the target object in the member function

3. Member functions with default parameter values

4. Inline functions

1.3 Constructor and destructor

1.3.1 Constructor:

1.3.2 Default constructor and destructor

 1.3.4 Classification and call of constructor

 1.3.5 When to call the copy constructor

1.3.6 Constructor calling rules

1.3.7 Supplementary functions

1. Delegating constructor

2. Move constructor

 3. default, delete function

1.4 Combinations of classes

1.4.1 Combination

1.4.2 Forward reference declarations

 4.5 Supplements to initialization lists

 4.6 Structure

Summarize:


 

Class and Object Mind Map

63f596209e904fcf92d53e83c811abf2.png


I believe you already have a preliminary understanding, continue reading

 

1.1 The basic characteristics of object-oriented programming

1.1.1 Abstraction

 Abstraction is a generalization of specific problems (objects). The abstraction of the process of extracting and describing the public properties of a class of objects
 includes two aspects: data abstraction and behavioral abstraction (functional abstraction and code abstraction)

int hour,minute,second//数据抽象
showtTme();setTime();//功能抽象

 1.1.2 Packaging

Encapsulation is to combine abstracted data and functions to form an organic whole (class), in which data and functions are members of the class.


Why package?


Through encapsulation, a small number of old members act as the interface between the class and the outside, while other members are hidden, so as to achieve reasonable control of member access rights, minimize the impact between different classes, and enhance data security. and simplify programming


1.1.3 Inheritance

> It enables the attributes and behaviors in the general concept to be shared by the special concept, getting rid of the dilemma of repeated analysis and repeated development *. The C++
> language provides a class inheritance mechanism, allowing programmers to make more specific and detailed
> descriptions on the basis of maintaining the original class characteristics. Through this hierarchical structure of classes, the relationship between special concepts and general concepts can be well reflected.


 1.1.4 Polymorphism

> Broadly speaking, polymorphism refers to the ability of a program to handle multiple types of objects . In C++ language, this
kind of polymorphism can be realized through four forms of mandatory polymorphism, overloaded polymorphism, type parameterized polymorphism, and polymorphism


 1.2 Classes and Objects

1.2.1 Class definition

//以时钟为例
class Clock										//class关键字,类名
{												//边界
public:											//外部接口
    void setTime(int newH,int newM,int newS);	//行为,代码成员
    void showTime();							//行为,代码成员
private:										//特定的访问权限
    int m_Hour,m_Minute,m_Second;				//属性,数据成员
}												//边界

1.2.2 Class Access Control

532dddd7e0094057b112387f681c4cd3.png

 


1.2.3 Objects

> Class is actually an abstract mechanism. It describes the common attributes and behaviors of a class of things.
>
> In the C++ language, the object of a class is a specific entity (also called an instance) of the class.
> If the employees of the entire company are regarded as a class, then each employee is a specific entity of the class. That is, an object

Declaring an object is the same as declaring a general variable: class name + object name

Clock my clock	//声明了一个时钟变量

Note: Note that the memory space occupied by objects is only used to store data members, and function members do not store copies in each object. The code of each function only occupies one space in memory


1.2.4 Member functions of classes

Unlike ordinary functions, the name of the class must be specified when implementing member functions.

1. Member function implementation

/*
返回值类型  类名 :: 函数成员名(参数表)
{
	函数体
}
*/
void Clock::setTime(int newH,int newM,int newS)
{
    hour = newH;
    minute = newM;
    second = newS;
}
void Clock::showTime()
{
    cout<<hour<<":"<<minute<<":"<<second<<endl;
}

2. Call the target object in the member function

> Destination object in member function call The difference between calling a member function and calling an ordinary function is that the "." operator needs to be used to indicate the object to be called. This object is called the destination object in this call. For example, use " myClock.showTime()" calls the showTime function. myClock is the target object in this calling process

Note: Note that in the member functions of the class, both the private members of the target object and the private members of other objects of the current class can be accessed

3. Member functions with default parameter values

Class member functions can also have default parameter values ​​like ordinary functions, but **default values ​​​​must be written in the class definition**

class Clock
{
 public:
    void setTime(int newH = 0, int newM = 0,int newS = 0);
    ……
}

4. Inline functions

> We know the inline member function. The calling process of the function consumes some memory resources and running time to pass parameters and return values, and to record the state at the time of calling, so as to ensure that it can return correctly and continue to execute after the call is completed. If some function members need to be called frequently, and the code is relatively simple , this function can also be defined as an inline function (inline function)

Note: Inline functions will increase the length of the compiled code, so choose carefully after weighing the pros and cons

//1.隐式声明,将函数体直接放在类体里
class Clock
{
 public:
    //隐式声明
    void setTime(int newH = 0, int newM = 0,int newS = 0);
    ……
}
//2.显式声明:在函数体实现时,在函数返回值类型前面加上inline
inline void Clock::showTime()
{
    //::为域符
    ……
}

So much has been introduced, let’s review a complete program

#include<iostream>

usinq namespace stdi
//时钟类的定义
class Clocki
//外部接口,公有成员雨数
pwblic:

void setPime(int newH=0, int newM=0, int news = 0),
veldshowTime()
//私有数据成员
private:

int hour, minute,second;
//时钟类成员雨数的具体实现
void Clock:;setTime(int newH, int newN, int news) {
hour=newH
minute-newM;
second-newS;
inline void cloek::showTlme() (
cout<<hour<<";"<<minute<<";"<csecondx<endl;
//主雨数

int main() {

//定义对象myClock
Clock myClockx

cout<<"First time set and output:"<<end1;
//设置时间为默认值
myClock.setTime()

//显示时间
myClock.showTime()
cout<<"Second time set and output:"<<endl;
//设置时间为 8: 30: 30
myClock.setrime(8, 30, 30)7

//显示时间
myClock.showTime();
return 0

(Hoohoo, it’s not easy. Above we have learned the specific definitions of classes and objects, as well as the basic introduction of = and member functions. After a short breath, let’s enter the introduction of specific functions)


 

1.3 Constructor and destructor

Remember : the data member setting when defining the object is the initial object (object creation process --> calling functions such as construction and destruction)

1.3.1 Constructor:

  • Initialization. It means that the initial value of the variable is written in it while the memory unit is allocated for the variable
  • When encountering an object definition, the program will apply to the operating system for a certain amount of memory space to store the newly created object

The function of the constructor is to construct the object with a specific value when the object is created. Initialize the object to a specific state . A constructor is also a member function of a class. In addition to the characteristics of a general member function, it also has some special
properties: the function name of the constructor is the same as the class name, and there is no return value; the constructor is usually declared as a public function


1.3.2 Default constructor and destructor

Default constructor syntax: `class name ( ) { }

  •  Constructor, no return value and no void
  • The function name is the same as the class name
  • Constructors can have parameters, so overloading can occur
  •  The program will automatically call the constructor when calling the object, no need to call it manually, and it will only be called once

Destructor syntax: `~class name() { }`

  • Destructor, no return value and no void
  • The function name is the same as the class name, and the symbol ~ is added before the name
  • Destructors cannot have parameters, so overloading cannot occur
  • The program will automatically call the destructor before the object is destroyed, no need to call it manually, and it will only be called once

Look at an example:

class Person
{

public:
	//构造函数
	Person()

	{
		cout << "Person的构造函数调用" << endl;
	}
    //析构函数
	~Person()
	{
		cout << "Person的析构函数调用" << endl;
	}
};

void test01()
{
	Person p;

}
int main() {
	test01();

	system("pause");
	return 0;
}

 1.3.4 Classification and call of constructor

*Two classification methods:*

  • ​*    According to the parameters, it can be divided into: construction with parameters and construction without parameters*
  • ​ *Divided by type: ordinary construction and copy construction*

*Three calling methods:*

  • ​*    Brackets*
  • ​ *Display method*
  • ​ *Implicit conversion method*

See the example below:

16d2e40c249c477f8ca7bdbb305f6379.png


 1.3.5 When to call the copy constructor

There are usually three situations in which the copy constructor is called in C++

  • Initialize a new object using an already created object
  • The way of passing by value is to pass values ​​to function parameters
  • returns the local object by value

Example:

#include<iostream>

using namespace std;

class Person
{
public:
	Person()
	{
		cout << "默认构造函数的调用" << endl;
	}
	Person(int age)
	{
		m_age = age;
		cout << "有参函数的调用" << endl;
	}
	Person(const Person& p)
	{
		m_age = p.m_age;
		cout << "拷贝函数的调用" << endl;
	}
	~Person()
	{
		cout << "析构函数的调用" << endl;
	}
	int m_age;
};

//2.值传递的方式给函数参数传值
//值传递其实就是要拷贝副本,拷贝函数会执行
void doWork(Person p)
{
}
//3.值方式返回局部变量
Person doWork2()
{
	Person p3;
	//值返回也是拷贝
	cout << (int*)&p3 << endl;
	return p3;
}
void test03()
{
	Person p = doWork2();
	cout << (int*)&p << endl;
}
void test02()
{	//	实参传递给形参有拷贝
	Person p;
	doWork(p);
}
void test01()
{
	Person p1(20);
	Person p2(p1);
	cout << "p2的年龄是: " << p2.m_age << endl;
}
int main() {
	//test01();
	//test02();
	test03();
	return 0;
}

operation result:

f0b495acd5f943b98d64fb8d8795bab4.png

 


1.3.6 Constructor calling rules

By default, the c++ compiler adds at least 3 functions to a class

  1. Default constructor (no parameters, function body is empty)
  2. Default destructor (no parameters, function body is empty)
  3. The default copy constructor, which copies the value of the property

The constructor call rules are as follows:

* If the user defines a constructor with parameters, C++ will not provide the default no-argument construction, but will provide the default copy construction
* If the user defines the copy constructor, C++ will not provide other constructors

Example:

class Person {
public:
	//无参(默认)构造函数
	Person() {
		cout << "无参构造函数!" << endl;
	}
	//有参构造函数
	Person(int a) {
		age = a;
		cout << "有参构造函数!" << endl;
	}
	//拷贝构造函数
	Person(const Person& p) {
		age = p.age;
		cout << "拷贝构造函数!" << endl;
	}
	//析构函数
	~Person() {
		cout << "析构函数!" << endl;
	}
public:
	int age;
};
void test01()
{
	Person p1(18);
	//如果不写拷贝构造,编译器会自动添加拷贝构造,并且做浅拷贝操作
	Person p2(p1);

	cout << "p2的年龄为: " << p2.age << endl;
}

void test02()
{
	//如果用户提供有参构造,编译器不会提供默认构造,会提供拷贝构造
	Person p1; //此时如果用户自己没有提供默认构造,会出错
	Person p2(10); //用户提供的有参
	Person p3(p2); //此时如果用户没有提供拷贝构造,编译器会提供
	//如果用户提供拷贝构造,编译器不会提供其他构造函数
	Person p4; //此时如果用户自己没有提供默认构造,会出错
	Person p5(10); //此时如果用户自己没有提供有参,会出错
	Person p6(p5); //用户自己提供拷贝构造
}
int main() {
	test01();
	system("pause");
	return 0;
}

operation result:

307c6d4be5d141dbbc8362fd5659b59f.png

 


1.3.7 Supplementary functions

1. Delegating constructor

> A delegating constructor uses other constructors of its class to perform its own initialization process. That is to say, it delegates some (or all ) of its responsibilities to other constructors. We use delegating constructors to override the construction of the Clock class function. Its form is as follows:

//构造函数
Clock(int newH, int newM, int newS) {
hour=newH;
minute=newN;

second=newS;
//构造函数
Clock() :Clock(0, 0,0) {}
/*可以看到第二个构造函数委托给了第一个构造函数来完成数据成员的初始化。当一个构造
函数委托给另一个构造函数时,受委托的构造函数的初始值列表和函数体依次执行,然后控
制权才会交还给委托者函数。*/

2. Move constructor

Refer to books:

fc59ed5fc6db49a6aabeaf9e4b7a455c.png

 


 3. default, delete function

> Default constructor, copy constructor and move constructor. These concepts are confusing. When defining a new class, users may just want to use it simply. Don't want to spend too much effort on copy control optimization performance. C++ The 11th standard provides two keywords, default and delete, to simplify the definition and use of constructors. Use =delault to explicitly ask the compiler to automatically generate a default or copy constructor.

Take a chestnut:

class MyStr {
public:
string sr
//默认合成的无参构造函数
MyStr()=default;
//有参构造函数
NyStr(string _s) : s(std::move(_s)) {};
//默认合成的复制构造函数
MyStr(MyStr ssstr)=default;
//默认合成的析构函数
~MyStr()=default;
};

There is still one:

class MyStr {
public:
string s;
//默认合成的无参物造函数
MyStr()=default;
//有参构造函数
MyStr(string_s) : s(std::move(_s)) ();
//删除复制构造函数
NyStr(NyStr ssstr)=deleter
//默认合成的析构函数
~MyStr()=default;
};

1.4 Combinations of classes

1.4.1 Combination

A member of a C++ class can be an object of another class, we call this member an object member

For example:

class A {}
class B
{
    A a;
}

Class B has object A as a member, and A is an object member

expand the concept

 

The combination of classes describes the situation that a class embeds objects of other classes as members. The relationship between them is a
relationship of inclusion and inclusion.

For example, a class is used to describe a computer system. First, it can be decomposed into hardware and software. The hardware includes a central processing unit (Central Processing Unit. CPU), memory, input devices and output devices. Software can include system software and applications software. Each of these parts can be further decomposed and described in terms of classes. It is a composition of classes. Figure 4-3 shows their interrelationships. Combinations can be used to describe slightly complicated problems. This is more in line with the thinking law of gradual refinement

When creating an object of a class. If this class has embedded object members, then each embedded object will be automatically created
because the component object is part of a complex object. Therefore, when creating an object, it is necessary to
initialize both the basic type data members of this class and the embedded object members
. At this point, it is important to understand the order in which the constructors of these objects are called

76da2bd339ca4133a037d7fbfa3094ef.png

 


order:

  •  Call the constructor of the embedded object. The calling order is in accordance with the order in which the embedded objects appear in the definition of the composite class
  • The order in which embedded objects appear in a constructor's initialization list is independent of the order in which the embedded object constructors are called.
  • Execute the function body of the constructor of this class

Notice:

​ **The call execution order of the destructor is just opposite to that of the constructor**


1.4.2 Forward reference declarations

Just look at an example to understand:

//A类的定义
class A{
//外部接口
Public:
//以B类对象b为形参的成员雨数
void f(B b);
//这里将引起编译错误,因为“B"为未知符号
//B类的定义
class B{
//外部接口
public:
//以A类对象a为形参的成员雨数
void g(A a);
};

To solve this problem, we need to use forward reference declaration (see code below)

class B; //前向引用声明 <----------很有效
//A类的定义
class A{
//外部接口
Public:
//以B类对象b为形参的成员雨数
void f(B b);
//这里将引起编译错误,因为“B"为未知符号
//B类的定义
class B{
//外部接口
public:
//以A类对象a为形参的成员雨数
void g(A a);
};

 4.5 Supplements to initialization lists

effect:

C++ provides initialization list syntax to initialize properties

Syntax: `constructor():property1(value1),property2(value2)...{}

Example:

class Person {
public:

	传统方式初始化
	//Person(int a, int b, int c) {
	//	m_A = a;
	//	m_B = b;
	//	m_C = c;
	//}

	//初始化列表方式初始化 
	Person(int a, int b, int c) :m_A(a), m_B(b), m_C(c) {}
	void PrintPerson() {
		cout << "mA:" << m_A << endl;
		cout << "mB:" << m_B << endl;
		cout << "mC:" << m_C << endl;
	}
private:
	int m_A;
	int m_B;
	int m_C;
};

int main() {

	Person p(1, 2, 3);
	p.PrintPerson();


	system("pause");

	return 0;
}

        


It's not easy to see the little friends here, and it's the last section soon, persistence is victory!

 4.6 Structure

First, let's explain the big difference between classes and structures:

**The default access type of Class is private type, while the structure is public. **

The only **difference** between struct and class in C++ is that **the default access rights are different**

the difference:

  • struct default permissions are public
  • class default permission is private
class C1
{
	int  m_A; //默认是私有权限
};
struct C2
{
	int m_A;  //默认是公共权限
};
int main() {

	C1 c1;
	c1.m_A = 10; //错误,访问权限是私有

	C2 c2;
	c2.m_A = 10; //正确,访问权限是公共

	system("pause");

	return 0;
}

Summarize:

Well, the knowledge points about encapsulation in C++ classes and objects and so on are introduced here. With only 7000 words, it is far from being able to fully introduce the knowledge of C++ classes and objects. Of course, it is also limited by the author's level. Criticism and correction are welcome. Previous exchanges and learning progress!

 

おすすめ

転載: blog.csdn.net/m0_73421035/article/details/130009533