[Introduction to C++ Phase 4] Classes and Objects (Part 1)

foreword

The C language is process-oriented, focusing on the process, analyzing the steps to solve the problem, and solving the problem step by step through function calls.

C++ is an object-oriented language with three major features of object-oriented: inheritance, encapsulation, and polymorphism. But since it is an introductory article, it would be too difficult for everyone to explain these clearly at the beginning.
Please add a picture description

Everyone first understands a class as: a functional interface and a data packet , and the function that needs to be called directly calls its interface to get the result

When using the interface, we don't need to know the specific implementation, we only need to know its function

use of class

Don’t worry about the implementation, let’s take a look at the pig running (the use of classes)

#include<iostream>
#include<string.h>

struct student//学生类
{
    
    
	student(const char* number ,const char* name)
	{
    
    
		strcpy(_number, number);
		strcpy(_name, name);
	}
	void print()
	{
    
    
		printf("姓名:%s  学号:%s\n", _name, _number);
	}
	char* number()
	{
    
    
		return _number;
	}
	char* name()
	{
    
    
		return _name;
	}
	char _number[15];
	char _name[15];
};
int main()
{
    
    
//类型为student ,对象名为zhang_san,()中是传参
	student zhang_san("20013", "张三");
	student li_si("20015", "李四");

	zhang_san.print();// .直接调用print接口即可
	//获取li_si对象中的_name变量中的数据
	std::cout << li_si._name << std::endl;
}

As above, I defined the student class, which has the function of printing out student information, and student number (_number) student name (_name)

When using, we only need to define the student object to use the functions in the student and obtain the variable data in the class.
insert image description here
But the definition of the above structure is preferred to use class instead in C++

class definition

class className
{
    
    
	//类体:由成员变量和成员函数组成

};  //注意后面要加分号结束

class is the keyword to define the class, ClassName is the name of the class, and {} is the body of the class. Note that the semicolon after the end of the class definition
cannot be omitted.

The contents of the class body are called members of the class : variables in the class are called attributes or member variables of the class; functions in the class are called methods or member functions of the class.

There are two ways to define a class:

  1. The member function declaration and definition are all placed in the class body .
    Note : If the member function is defined in the class, the compiler may treat it as an inline function.
    insert image description here
    2. The class declaration is placed in the .h file, and the member function definition is placed in the .cpp file

    Note: The class name:: needs to be added before the definition of the member function name, indicating that the function belongs to this class
    insert image description here
    . In general, the second method is preferred .

Suggestions for defining member variable names

insert image description here

class access qualifier

The way of C++ to achieve encapsulation : use the class to combine the properties and methods of the object to make the object more perfect, and selectively provide its interface to external users through access rights

insert image description here
Access qualifier description :

  1. Publicly modified members can be directly accessed outside the class
  2. Protected and private modified members cannot be directly accessed outside the class (protected and private are similar here), let’s talk about the difference between the two when writing inheritance, if you talk too much, I’m afraid everyone will be confused

Access scope :

  1. from the occurrence of this access-qualifier until the occurrence of the next access-qualifier
  2. If there is no access qualifier, the scope will be }, that is, the end of the class
    insert image description here
    If there is no access qualifier in the class :
    the default access right of class is private, and struct is public (because struct is compatible with C)

class scope

Since classes create scope, all members of a class are within the scope of the class. When defining a member of a class outside the class, you need to use the ::
scope operator to indicate which class domain the member belongs to
.

void car::print()//car::声明print()属于类car这个作用域
{
    
    
	cout << _name << _price << endl;
}
class car
{
    
    
public:
	void print();//声明
private:
	char _name[20] ;//车名
	char _price[20];//价格
};

class instantiation

A class is a description of an object . It is a model-like thing, which defines which members a class has, and defines a class
without allocating actual memory space to store it; for example: the form filled out when a 4S store car enters the warehouse, The table can be regarded as a class to describe vehicle information.

To use an analogy: a class is like an architectural blueprint (a picture is just an idea or a plan is virtual), and we can use this blueprint to build multiple buildings that are as real as they are.

The class is also the same before the object is generated, its function cannot be used, and the object needs to be instantiated.

As shown in the figure below, a class needs to define an object before it can be used. The process of creating an object with a class type is called the instantiation of a class

class car
{
    
    
public:
	void print();

	char _name[20] ;//车名
	char _price[20];//价格
};
void car::print()//car::声明print()属于类car
{
    
    
	cout << "车名:" << _name << " 价格:" << _price << endl;
}
int main()
{
    
    
	//car.print();//会报错,类是不能直接使用的
	
	//正确方法
	car Byd_q;//定义出对象Byd_q 
	strcpy(Byd_q._name, "比亚迪秦");//向对象中写入数据
	strcpy(Byd_q._price, "99800");//向对象中写入数据
	Byd_q.print();//调用对象的成员含函数
}

How to define an object

类名 对象名;

How to calculate class size

class A1
{
    
    
public:
	void fun()
	{
    
    
		cout << "zhu_ge_bin";
	}
	int _a;
};
class A2
{
    
    
public:
	int _a;
};
class A3
{
    
    
public:

};
int main()
{
    
    
	A1 d1;
	A2 d2;
	A3 d3;
	printf("A1对象的大小为:%d\n", sizeof(d1));
	printf("A2对象的大小为:%d\n", sizeof(d2));
	printf("A3对象的大小为:%d\n", sizeof(d3));
}

As shown in the figure above, the result of the operation
insert image description here
can be seen that the size of a class is actually the sum of "member variables" in the class. Of course, attention should be paid to memory alignment

Note : the size of the empty class, the empty class is special, the compiler gives the empty class a byte to uniquely identify the object of this class

Someone here may ask if the functions in that class don't take up space?

1: The storage space occupied by each object is only the storage space occupied by the data part of the object, not including the storage space occupied by the function code . (I will learn later that virtual base class pointers and virtual function pointers also belong to the data part and can be ignored for now)
2: The member functions of the class themselves do not occupy the memory space of the object. They are just part of the class, stored in the code section.
3: Therefore, different objects share the same function code, which saves memory space.

Structure memory alignment rules

Structure memory alignment rules

  1. The first member is at offset 0 of the structure.
  2. Other member variables should be aligned to an address that is an integer multiple of a certain number (alignment number).
    Note: Alignment = the smaller value between the default alignment of the compiler and the size of the member , and the default alignment in VS is 8
  3. The total size of the structure is: an integer multiple of the maximum alignment number (the largest of all variable types and the smallest default alignment parameter).
  4. If a structure is nested, the nested structure is aligned to an integer multiple of its own maximum alignment, and the
    overall is an integer multiple of all maximum alignments (including the alignment of the nested structure) .

this pointer

First look at the following code and run

class car
{
    
    
public:
	void print()
	{
    
    
		cout << "车名:" << _name << " 价格:" << _price << endl;
	}
	void Init(const char* name , const char* price)
	{
    
    
		strcpy(_name , name);//写入数据
		strcpy(_price , price);//写入数据
	}
private:
	char _name[20];//车名
	char _price[20];//价格
};
void test4()
{
    
    
	car Byd_q;//定义出对象Byd_q
	car Byd_s;//定义出对象Byd_s
	Byd_q.Init("比亚迪 秦" , "99800");//向对象中写入数据
	Byd_s.Init("比亚迪 宋" , "154800");//向对象中写入数据

	Byd_q.print();//调用对象的打印函数
	Byd_s.print();//调用对象的打印函数
}

The result is as
insert image description here
follows. It is said that the object has only data, and the functions of the class are shared. Then why do different objects of the class call the same function with different results (note: make sure that the data in the object is different)

In C++, this problem is solved by introducing the this pointer, that is: the C++ compiler adds a hidden
pointer parameter to each "non-static member function", so that the pointer points to the current object (the object that calls the function when the function is running), All "member variable" operations in the function body
are accessed through this pointer. It's just that all operations are transparent to the user, that is, the user does not need to pass it, and the compiler
completes it automatically.
When the above code calls the member function to pass parameters, it seems that only some basic data is passed in, but actually a pointer to the object is also passed in:
insert image description here

Characteristics of this pointer

  1. The type of this pointer: class type * const, that is, in member functions, the this pointer cannot be assigned a value.
  2. Can only be used inside a "member function"
  3. The this pointer is essentially a formal parameter of a "member function". When an object calls a member function, the object address is passed as an actual parameter to
    this formal parameter. So the this pointer is not stored in the object.
  4. The this pointer is the first implicit pointer parameter of the "member function". Generally, it is automatically passed by the compiler through the ecx register
    and does not need to be passed by the user.

Guess you like

Origin blog.csdn.net/ZhuGeBin26/article/details/130374666