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


Insert image description here

1. Preliminary understanding of process-oriented and object-oriented

C语言是面向过程的,关注的是过程,分析出求解问题的步骤,通过函数调用逐步解决问题。
Insert image description here
Insert image description here


C++是基于面向对象的,关注的是对象,将一件事情拆分成不同的对象,靠对象之间的交互完成。

Insert image description here
)



2. Introduction of classes

C语言结构体中只能定义变量,在C++中,结构体内不仅可以定义变量,也可以定义函数。

For example: in the initial stage of data structure, when the stack was implemented in C language, only variables could be defined in the structure; now when it is implemented in C++, you will find that functions can also be defined in the struct.

typedef int DataType;
struct Stack
{
    
    
    void Init(size_t capacity)
    {
    
    
        _array = (DataType*)malloc(sizeof(DataType) * capacity);
        if (nullptr == _array)
        {
    
    
            perror("malloc申请空间失败");
            return;
        }
        _capacity = capacity;
        _size = 0;
    }
    void Push(const DataType& data)
    {
    
    
        // 扩容
        _array[_size] = data;
        ++_size;
    }
    DataType Top()
    {
    
    
        return _array[_size - 1];
    }
    void Destroy()
    {
    
    
        if (_array)
        {
    
    
            free(_array);
            _array = nullptr;
            _capacity = 0;
            _size = 0;
        }
    }
    DataType* _array;
    size_t _capacity;
    size_t _size;
};
int main()
{
    
    
    Stack s;
    s.Init(10);
    s.Push(1);
    s.Push(2);
    s.Push(3);
    cout << s.Top() << endl;
    s.Destroy();
    return 0;
}

The definition of the structure above is preferred to be replaced by class in C++.



3. Class definition

class className
{
    
    
    // 类体:由成员函数和成员变量组成
    // 一定要注意后面的分号
};

class is the keyword that defines the class, ClassName is the name of the class, and { } is the body of the class. Note that the semicolon at the end of the class definition cannot be omitted.
The contents in 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.

Two ways to define classes:

1. 声明和定义全部放在类体中,需注意:成员函数如果在类中定义,编译器可能会将其当成内 联函数处理。
Insert image description here
2. 类声明放在.h文件中,成员函数定义放在.cpp文件中,注意:成员函数名前需要加类名::
Insert image description here
Under normal circumstances, the second method is more expected.
Suggestions on naming rules for member variables:

// 我们看看这个函数,是不是很僵硬?
class YYQ
{
    
    
public:
	 void Init(int year)
 {
    
    
	 // 这里的year到底是成员变量,还是函数形参?
	 year = year;
 }
private:
	 int year;
};

// 所以一般都建议这样
class YYQ
{
    
    
public:
	 void Init(int year)
	 {
    
    
	   _year = year;
	 }
private:
	 int _year;
};

// 或者这样
class YYQ
{
    
    
public:
 void Init(int year)
 {
    
    
	 mYear = year;
 }
private:
	 int mYear;
};
// 其他方式也可以的,主要看公司要求。一般都是加个前缀或者后缀标识区分就行


4. Class access qualifiers and encapsulation

4.1 Access qualifiers

The way C++ implements encapsulation: use classes to combine the properties and methods of objects to make the objects more complete, and selectively provide their interfaces to the outside through access permission selection
of users.

Insert image description here
[Access Qualifier Description]

  1. Members modified by public 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)
  3. The access scope begins at the occurrence of this access qualifier and ends at the occurrence of the next access qualifier.
  4. If there is no access qualifier later, the scope ends at }, which is the end of the class.
  5. The default access rights of class are private and struct is public (because struct must be 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.


Learn now and use now
【面试题】

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 in C++ can also be used to define classes. It is the same as class definition. The difference is

struct定义的类默认访问权限是public, class定义的类 默认访问权限是private。

Note that for the sake of code readability, we still write all access qualifiers
Note: There is also a difference between struct and class in inheritance and template parameter lists. Let me introduce it to you.


4.2 Packaging

【面试题】

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

  • In the class and object stage, we mainly study the encapsulation characteristics of classes. So what is encapsulation?

Encapsulation: Organically combine data and methods of operating data, hide the properties and implementation details of the object, and only expose the interface to the outside world to
interact with the object.
Encapsulation is essentially a kind of management that makes it easier for users to use classes. For example: For a complex device like a computer, the only things provided to the user are the power on/off button, keyboard input, monitor, USB jack, etc., allowing the user to interact with the computer and complete daily tasks. Routine affairs. But in fact, the real work of the computer is the CPU, graphics card, memory and other hardware components. For computer users, they do not need to worry about the internal core components, such as how the circuits on the motherboard are laid out, how the internals of the CPU are designed, etc. All you need to know is how to turn on the computer and how to interact with the computer through the keyboard and mouse. Therefore, when computer manufacturers leave the factory, they put a shell on the outside to hide the internal implementation details, and only provide the switch, mouse and to the outside world. Keyboard jacks, etc., allow the user to interact with the computer. Encapsulation is implemented in the C++ language. Data and methods of operating data can be organically combined through classes, and access permissions are used to hide the internal implementation details of the object and control it. Which methods can be used directly outside the class.


Insert image description here







5. Scope of class

The class defines a new scope, and all members of the class are within the scope of the class. When defining members outside a class, you need to use the ::
scope operator 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;
}


6. Instantiation of classes

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

  1. A class describes an object. It is something like a model. It limits the members of the class. Defining a class does not allocate actual memory space to store it; for example: the student information form filled in when enrolling, a form can be Think of it as a class to describe specific student information.

A class is like a riddle, describing the answer, and the answer is an instance of the riddle.
谜语:"年纪不大,胡子一把,主人来了,就喊妈妈" 谜底:山羊

  1. A class can instantiate multiple objects. The instantiated objects occupy actual physical space and store class member variables.
int main()
{
    
    
 Person._age = 100;   // 编译失败:error C2059: 语法错误:“.”
 return 0;
}

The Person class has no space, and only objects instantiated by the Person class have specific ages.

  1. Let’s use an analogy. Instantiating objects from a class is like using architectural design drawings to build a house in reality. A class is like a design drawing. It only designs what is needed, but there is no physical building. Similarly, a class is just a design that is instantiated. Objects can actually store data and occupy physical space.
    Insert image description hereInsert image description here


7. Class object model

7.1 How to calculate the size of a class object

class A
{
    
    
public:
void PrintA()
{
    
    
   cout<<_a<<endl;
}
private:
char _a;
};

问题:类中既可以有成员变量,又可以有成员函数,那么一个类的对象中包含了什么?如何计算 一个类的大小?

7.2 Guessing the storage method of class objects

  • The object contains various members of the class

Insert image description here
Defect: The member variables in each object are different, but the same function is called. If stored in this way, when a
class creates multiple objects, each Each object will save a copy of the code, and the same code will be saved multiple times, which wastes space. So
how to solve it?

  • Only one copy of the code is saved, and the address where the code is stored is saved in the object.

Insert image description here

  • Only member variables are saved, and member functions are stored in the public code section.

Insert image description here

Question: Regarding the above three storage methods, which method does the computer store?

// 类中既有成员变量,又有成员函数
class A1 {
    
    
public:
    void f1(){
    
    }
private:
    int _a;
};
// 类中仅有成员函数
class A2 {
    
    
public:
   void f2() {
    
    }
};
// 类中什么都没有---空类
class A3
{
    
    };

sizeof(A1) : ______ sizeof(A2) : ______ sizeof(A3) : ______
Conclusion: The size of a class is actually the sum of the "member variables" in the class , of course pay attention tomemory alignment

注意空类的大小,空类比较特殊,编译器给了空类一个字节来唯一标识这个类的对象。

7.3 Structure memory alignment rules

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


8.this pointer

8.1 Introduction of this pointer

Let's first define a date class Date

#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
using namespace std;

class Date
{
    
    
public:
	void Init(int year, int month, int day)
	{
    
    
		_year = year;
		_month = month;
		_day = day;
	}
	void Print()
	{
    
    
		cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	int _year; //年
	int _month; //月
	int _day; //日
};
int main()
{
    
    
	Date d1, d2;
	d1.Init(2023, 10, 12);
	d2.Init(2022, 10, 12);
	d1.Print();
	d2.Print();
	return 0;
}

For the above class, there is such a problem:
There are two member functions, Init and Print, in the Date class. There is no distinction between different objects in the function body. Then when d1 calls Init function, how does the function know that it should set the d1 object instead of the d2 object?

C++ solves this problem by introducing the this pointer, that is: the C++ compiler adds a hidden pointer parameter to each "non-static member function", allowing the pointer to point to the current object (the object that calls the function when the function is running). All operations on "member variables" in the function body are accessed through this pointer.
只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成。


It is actually written like the picture below, but the formal and actual parameters of writing this cannot be displayed.
Insert image description here

8.2 Characteristics of this pointer

  1. The type of this pointer: class type * const, that is, in member functions, 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 to the this parameter as an actual parameter. Therefore, 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.

Insert image description here
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_58286439/article/details/134355196