[C++] Classes and Objects (Part 1)

introduction

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 based on object-oriented, focusing on objects, splitting one thing into different objects, and relying on the interaction between objects to complete.

C++ is not a pure object-oriented language.

classes and objects

class introduction

In C language, only variables can be defined in the structure. In C++, not only variables but also functions can be defined in the structure.

struct Student
{
    
    
	void SetStudentInfo(const char* name, const char* gender, int 			age)
	{
    
    
		strcpy(_name, name);
		strcpy(_gender, gender);
		_age = age;
	}
	void PrintStudentInfo()
	{
    
    
		cout<<_name<<" "<<_gender<<" "<<_age<<endl;
	}
	char _name[20];
	char _gender[3];
	int _age;
};

int main()
{
    
    
	Student s;
	s.SetStudentInfo("Peter", "男", 18);
	return 0;
}

The definition of the above structure, in C++, prefer to use class instead

class definition

insert image description here

class is the keyword for defining a class, ClassName is the name of the class, and {} is the body of the class. Note the semicolon at the end of the class definition.

Elements in a class are called members of a class: data in a class is called attributes or member variables of the class; functions in a class are called methods or member functions of the class.

There are two ways to define a class:

  1. All declarations and definitions are placed in the class body. Note that if a member function is defined in a class, the compiler may treat it as an inline function.insert image description here

  2. Declarations are placed in .h files, and class definitions are placed in .cpp files.insert image description here

Class access qualifiers and encapsulation

The way C++ implements encapsulation: use classes to combine the attributes and methods of an object to make the object more complete, and selectively provide its interface to external users through access rights .
insert image description here

【Access Qualifier Description】

  1. Public modified members can be accessed directly outside the class
  2. Protected and private modified members cannot be directly accessed outside the class (protected and private are similar here)
  3. The scope of access rights begins at the occurrence of this access qualifier until the occurrence of the next access qualifier
  4. The default access permission of class is private, and struct is public (because struct is compatible with C)

Note: access qualifiers are only useful at compile time, when the data is mapped to memory, there is no difference in access qualifiers

Question: What is the difference between struct and class in C++?
Answer: C++ needs to be compatible with C language, so struct in C++ can be used as a structure. In addition, struct can also be used to define classes in C++.
It is the same as class is to define a class, the difference is that the default access mode of members of struct is public, and the default access mode of members of class is private.

The three major characteristics of object-oriented: encapsulation, inheritance, polymorphism.

Encapsulation: Organically combine data with methods for manipulating data, hide the properties and implementation details of objects, and only expose interfaces to interact with objects.

Encapsulation is essentially a management: we use class data and methods to encapsulate them. We don't want others to see, we use protected/private to encapsulate members. Open some common member functions for reasonable access to members. So encapsulation is essentially a management.

class scope

A class defines a new scope, and all members of the class are in the scope of the class. To define members outside the class body, you need to use the :: scope resolver to indicate which class scope the member belongs to.

class Person
{
    
    
public:
	void PrintPersonInfo();
private:
	char _name[20];
	char _gender[3];
	int _age;
};
// 这里需要指定PrintPersonInfo是属于Person这个类域
void Person::PrintPersonInfo()
{
    
    
	cout<<_name<<" "_gender<<" "<<_age<<endl;
}

instantiation of the class

The process of creating an object with a class type is called instantiation of the class.

1. A class is just a model-like thing, which defines the members of the class. Defining a class does not allocate actual memory space to store it.
2. A class can instantiate multiple objects, and the instantiated objects occupy the actual physical space and store class member variables.
3. For example: instantiating an object from a class is like building a house using architectural drawings in reality. A class is like a blueprint. It only designs what it needs, but there is no physical building. Similarly, a class is just a Design, instantiated objects can actually store data and occupy physical space.

Note: Member variables belong to objects, and they are defined when the object is instantiated. Variable and object definitions are open spaces. It doesn't matter if it is initialized or not.

Conclusion:
1. The size of a class is actually the sum of the "member variables" in the class. Of course, memory alignment is also required. Pay attention to the size of the empty class. The empty class is special. The compiler gives the empty class a byte to uniquely Identifies this class.
2. When calculating the size of a type, or a class object, only member variables are considered, because only member variables are stored in the object, and no member functions are stored. The address of the member function is not stored in the object, there is a common code segment.

Structure memory alignment rules:

  1. The first member is at the address at offset 0 from the structure.
  2. Other member variables should be aligned to an address that is an integer multiple of a number (alignment number). Note: Alignment = the smaller of the compiler's default alignment and the size of the member. The default number of alignments 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 number, and the overall size of the structure is an integer multiple of all maximum alignment numbers (including the alignment number of nested structures).

this pointer

derivation of this pointer

class Date
{
    
    
public :
	void Display ()
	{
    
    
		cout <<_year<< "-" <<_month << "-"<< _day <<endl;
	}
	void SetDate(int year , int month , int day)
	{
    
    
		_year = year;
		_month = month;
		_day = day;
	}
private :
	int _year ; // 年
	int _month ; // 月
	int _day ; // 日
};
int main()
{
    
    
	Date d1, d2;
	d1.SetDate(2018,5,1);
	d2.SetDate(2018,7,1);
	d1.Display();
	d2.Display();
	return 0;
}

For the above class, there is such a problem:
There are two member functions, SetDate and Display, in the Date class. There is no distinction between different objects in the function body. When s1 calls the SetDate function, how does the function know that the s1 object should be set, instead of setting the s2 object?

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.

Properties of this pointer

  1. type of this pointer: class type * const
  2. can only be used inside a "member function"
  3. This pointer is actually a formal parameter of a member function. When an object calls a member function, the object address is passed as an actual parameter to the this 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.

The this pointer is a formal parameter, and the formal parameters and local variables in the function are stored in the function stack frame, so the this pointer can be considered to exist on the stack.

Guess you like

Origin blog.csdn.net/qq_46994783/article/details/123473238