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

5a2585dded9b416fb4ea58637b42ed39.png

  Yan-yingjie's homepage

Awareness of the past, not remonstrance, knowing the future, can be pursued  

C++ programmer, 2024 electronic information graduate student


Table of contents

macro function

inline function

Basic understanding of process-oriented and object-oriented

        Process Oriented: Pay more attention to the process

        Object-Oriented: More Result-Oriented

class reference

this pointer

        Where does this pointer exist?

Comparison between C language and C++ to implement stack language

        C language implementation

        C++ implementation


macro function

        

        Advantages: no need to create stack frames, improving call efficiency

        Disadvantages: complex and easy to report errors, poor readability, unable to debug

inline function

        1. Func is not inline, how many lines of instructions total

                10000+50

        2. Func is inline, how many lines of instructions are there in total. 10000*50

        Executable program grows larger

        It is suitable for short and frequently called functions. Inlink is just a suggestion for the compiler. Whether to become inlink needs to be decided by the compiler. If the function is too long, inlink will not work to prevent code expansion. At the same time, the development of the language must be forward compatible. , The previous code cannot be changed. Once changed, some people's code or program will have a large number of bugs.

       NULL is actually a macro function, #define NULL 0

        Inline function, declaration and definition cannot be separated

inline int Add(int x,int y)
{
	return (x + y) * 10;
}


int main()
{
	for (int i = 0; i< 10000; i++)
	{
		printf("%d \n",i);
	}

}

Macro functions and inline functions are suitable for short and frequently called functions

Basic understanding of process-oriented and object-oriented

        Process Oriented: Pay more attention to the process

        Example: laundry

        Object-Oriented: More Result-Oriented

        Example: washing clothes 

        Split one thing into different objects, and rely on the interaction between objects to complete.

class reference

                Under normal circumstances, member variables are private, while methods are public, most companies in order to distinguish member variables and parameters

To distinguish between numbers, a bar will be added before or after the member variable

struct Stack
{
public:
	//成员函数
	void Init(int defaultCapacity = 4)
	{
		a = (int*)malloc(sizeof(int)* capacity);
		if (nullptr == a)
		{
			perror("malloc内容空间申请失败");
			return;
		}
		capacity = defaultCapacity;
		top = 0;
	}

	void Push(int x)
	{
		a[top++] = x;
	}

	void Destory()
	{
		free(a);
		a = nullptr;
		top = capacity;
	}

	//成员变量
private:
	int* a;
	int _top;
	int _capacity;
};

int main()
{
	struct Stack st1;
	st1.Init(20);
	Stack st2;
	st2.Init();
	st2.Push(1);
	st2.Push(2);
	st2.Push(3);
	st2.Push(4);
	st2.Destory();

	return 0;
}

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

       Encapsulation: organically combine data and methods of manipulating data, hide object attributes and implementation details, and only expose interfaces to the outside world

interact with objects.

        The essence of encapsulation is a kind of management, which makes it easier for users to use classes. For example: For a complex device such as a computer, the

The user only has the power-on button, through the keyboard input, monitor, and USB jack, allowing the user to communicate with the computer to complete the daily routine.

affairs. But in fact, the real work of the computer is the CPU, graphics card, memory and other hardware.

        For computer users, there is no need to care about the internal core plug-ins, such as how the lines on the motherboard are laid out, the CPU internal

How is it designed, etc., users only need to know how to turn on the computer and how to interact with the computer through the keyboard and mouse. because

When the computer manufacturer leaves the factory, it puts a shell on the outside to hide the internal implementation.

        

//类中仅有成员函数
class A2
{
public:
	void f2() {}
};

//类中什么都没有


class A3
{

};
int main()
{

    //没有成员变量的类对象,需要1byte,是为了占位,表示对象存在
    //不存储有效数据
	cout << sizeof(A2) << endl;
	cout << sizeof(A3) << endl;
}

        

this pointer

        this cannot be explicitly passed between formal parameters and actual parameters, but it can be used explicitly inside the function

        Where does this pointer exist?

        The this pointer is a formal parameter, which is a temporary copy of the actual parameter, stored in the stack space, as part of the stack frame

        Under VS, the this pointer is passed and optimized. The object address is placed in ecx, and ecx stores the value of this pointer.

        

        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 the formal parameter of the "member function" . When the object calls the member function, the object address is passed as the actual parameter to the 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.

        The this pointer is empty. Although the this pointer is called inside the function, it is not dereferenced, so no report occurs.

wrong, normal operation 

        The this pointer is empty, but the access to _a in the function is essentially this->a, and a is empty, so a crash occurs at runtime

Comparison between C language and C++ to implement stack language

        

        C language implementation

        

typedef int DataType;
typedef struct Stack
{
	DataType* array;
	int capacity;
	int size;
}Stack;
void StackInit(Stack* ps)
{
	assert(ps);
	ps->array = (DataType*)malloc(sizeof(DataType) * 3);
	if (NULL == ps->array)
	{
		assert(0);
		return;
	}
	ps->capacity = 3;
	ps->size = 0;
}
void StackDestroy(Stack* ps)
{
	assert(ps);
	if (ps->array)
	{
		free(ps->array);
		ps->array = NULL;
		ps->capacity = 0;
		ps->size = 0;
	}
}
void CheckCapacity(Stack* ps)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity * 2;
		DataType* temp = (DataType*)realloc(ps->array,
			newcapacity * sizeof(DataType));
		if (temp == NULL)
		{
			perror("realloc申请空间失败!!!");
			return;
		}
		ps->array = temp;
		ps->capacity = newcapacity;
	}
}
void StackPush(Stack* ps, DataType data)
{
	assert(ps);
	CheckCapacity(ps);
	ps->array[ps->size] = data;
	ps->size++;
}
int StackEmpty(Stack* ps)
{
	assert(ps);
	return 0 == ps->size;
}
void StackPop(Stack* ps)
{
	if (StackEmpty(ps))
		return;
	ps->size--;
}
DataType StackTop(Stack* ps)
{
	assert(!StackEmpty(ps));
	return ps->array[ps->size - 1];

}
int StackSize(Stack* ps)
{
	assert(ps);
	return ps->size;
}
int main()
{
	Stack s;
	StackInit(&s);
	StackPush(&s, 1);
	StackPush(&s, 2);
	StackPush(&s, 3);
	StackPush(&s, 4);
	printf("%d\n", StackTop(&s));
	printf("%d\n", StackSize(&s));
	StackPop(&s);
	StackPop(&s);
	printf("%d\n", StackTop(&s));
	printf("%d\n", StackSize(&s));
	StackDestroy(&s);
	return 0;
}
It can be seen that when implemented in C language, Stack- related operation functions have the following commonality:
  •         The first parameter of each function is Stack*
  •         The first parameter must be detected in the function, because the parameter may be NULL
  • In the function, the stack is manipulated         through the Stack* parameter
  • The address of the Stack structure variable         must be passed when calling
        Only the structure for storing data can be defined in the structure, and the method of operating data cannot be placed in the structure, that is, data and operation data
The method is separated , and the implementation is quite complicated, involving a lot of pointer operations, if you don’t pay attention, it may appear
wrong.

C++ implementation

typedef int DataType;
class Stack
{
public:
	void Init()
	{
		_array = (DataType*)malloc(sizeof(DataType) * 3);
		if (NULL == _array)
		{
			perror("malloc申请空间失败!!!");
			return;
		}
		_capacity = 3;
		_size = 0;
	}
	void Push(DataType data)
	{
		CheckCapacity();
		_array[_size] = data;
		_size++;
	}
	void Pop()
	{
		if (Empty())
			return;
		_size--;
	}
	DataType Top() { return _array[_size - 1]; }
	int Empty() { return 0 == _size; }
	int Size() { return _size; }
	void Destroy()
	{
		if (_array)
		{
			free(_array);
			_array = NULL;
			_capacity = 0;
			_size = 0;
		}
	}
private:
	void CheckCapacity()
	{
		if (_size == _capacity)
		{
			int newcapacity = _capacity * 2;
			DataType* temp = (DataType*)realloc(_array, newcapacity *
				sizeof(DataType));
			if (temp == NULL)
			{
				perror("realloc申请空间失败!!!");
				return;
			}
			_array = temp;
			_capacity = newcapacity;
		}
	}
private:
	DataType* _array;
	int _capacity;
	int _size;
};
int main()
{
	Stack s;
	s.Init();
	s.Push(1);
	s.Push(2);
	s.Push(3);
	s.Push(4);

	printf("%d\n", s.Top());
	printf("%d\n", s.Size());
	s.Pop();
	s.Pop();
	printf("%d\n", s.Top());
	printf("%d\n", s.Size());
	s.Destroy();
	return 0;
}

        

        In C++, the data and the methods of manipulating the data can be perfectly combined through the class, and those methods that can be called outside the class can be controlled through the access authority, that is, encapsulation. cognition of things. Moreover, each method does not need to pass the Stack* parameter, and the parameter will be automatically restored after the compiler compiles, that is, the Stack* parameter in C++ is maintained by the compiler, but in C language, it needs to be maintained by the user .

Guess you like

Origin blog.csdn.net/m0_73367097/article/details/131011153