C + + learning notes

catalogue

I Differences between C + + and C language structure

1.struct keyword

2. Functions are allowed in C + + structures

II Dynamic memory application of C language and C + +

1. malloc, calloc, realloc of C language.

2. Dynamic memory application of C + +

(1) Memory request for a single variable

(2) Dynamic memory request for array

(3) Structure dynamic memory request

III Memory pool

IV string type

1. Create a string

2. Basic operation of string

(1) Assignment copy

(2) Connect

(3) Compare

3. What is the difference between C language string and C + + string

4. Other interesting operations

I Differences between C + + and C language structure

1.struct keyword

The "struct" keyword is not required for definition, and the structure name can be used directly.

struct A
{
	char name[20];
	int age;
	//.....
};
int main()
{
	struct A a; //C language needs to add struct
	A aa; //C + + can be omitted
}

2. Functions are allowed in C + + structures

In C + +, we can regard the whole structure as an object. The data members in this object are called the properties of this object, and the member functions declared in this object are called the behavior or method of this object.

The implementation of member functions can be in the structure or outside the structure. To implement the member function outside the structure, you need to limit the function with the structure name.

struct A
{
	char name[20];
	int age;
	void Fun();
};
void A::Fun()
{
	//...
}

In the structure of C + +, its member function can directly access other members in the structure.

void A::Fun()
{
	cout << age << endl;
}

In terms of calling, C + + is basically the same as C language. Generally, there are three calling methods:

struct A
{
	char name[20];
	int age;
	void Fun();
};
void A::Fun()
{
	cout << age << endl;
}
int main()
{
	A a = {"Blue ",18};
	A* p = &a;
	a.age = 19;       //Object member
	p->age = 20;      //Object pointer - > member
	(*p).age = 21;    //(* object pointer) member
}

In addition, according to the knowledge of reference types learned last time, by taking the reference as the return value, we can create an interface in the structure that allows the external to change the internal properties of the structure. The specific implementation is as follows:

struct A
{
	char name[20];
	int age;
	int& getAge();
};
int& A::getAge()
{
	return age;
}
int main()
{
	A a = {"Blue ",18};
	a.getAge() = 19;
	//In fact, it is equivalent to: a.age = 19;
	cout << a.age << endl;
	//The print result is 19
}

This method looks a little silly in the structure, but there is an access permission problem in the class. This method is convenient. The introduction of the class will be updated in the next article. Here, click the table below.

II Dynamic memory application of C language and C + +

1. malloc, calloc, realloc of C language.

In short, malloc is a dynamic memory request without initialization.

int main()
{
	int* pMNum = (int*)malloc(sizeof(int) * 3);
	for (int i = 0; i < 3; i++)
	{
		cout << pMNum[i] << " ";
	}
	cout << endl;
}

You can see that the printed values are uninitialized garbage values. Let's look at the calloc for initialization:

int main()
{
	int* pCNum = (int*)calloc(3,sizeof(int));
	for (int i = 0; i < 3; i++)
	{
		cout << pCNum[i] << " ";
	}
	cout << endl;
}

You can see that the requested memory variables are initialized to 0.

The realloc # function is used to expand the dynamic memory on the basis of the original application. Note that the space after expansion must be larger than the original one.

int main()
{
	int* p = (int*)calloc(1, sizeof(int));
	if (!p) return 0;
	(*p) = 1999;
	p = (int*)realloc(p, sizeof(int)*3);
	if (!p) return 0;
	p[1] = 1;
	p[2] = 2;
	for (int i = 0; i < 3; i++)
	{
		cout << p[i] << " ";
	}
	free(p);
	return 0;
}

 

It can be seen that the original data is still stored in the heap and does not disappear, but it is expanded.

2. Dynamic memory application of C + +

(1) Memory request for a single variable

Single variable dynamic memory request is in parentheses.

int main()
{
	//Do not initialize when applying
	int* pInt = new int;
	*pInt = 123;
	delete pInt;
	pInt = nullptr;
	//Initialize on request
	int* pNum = new int(123);
	delete pNum;
	pNum = nullptr;
}

(2) Dynamic memory request for array

Dynamic memory requests for arrays are in curly braces. The following is the dynamic memory application of one-dimensional array:

int main()
{
	//Not initialized
	int* pInt = new int[3];
	delete[] pInt;
	pInt = nullptr;
	//initialization
	int* pNum = new int[3]{ 1,2,3 };
	delete[] pNum;
	pNum = nullptr;
}

Special attention should be paid to the fact that when it comes to the initialization of heap strings in both C language and C + +, they cannot be assigned directly, otherwise unexpected effects will occur. The following code is used to show:

int main()
{
	const char* pstr1 = new char[15];
	const char* pstr2 = pstr1;
	pstr1 = "I Love C++";
	cout << pstr1 << "\t" << pstr2 << endl;
}

It can be seen that there is no change in the dynamically applied space. The so-called assignment here only changes the direction of the pstr1 pointer. To assign values, use the strcpy function.

In fact, the dynamic memory application of two-dimensional array is similar to that of C language. They all apply for the space of secondary pointers first, and then apply for dynamic memory for the pointers in the array respectively, as follows:

​
int**& NewArr2D(int row,int col)
{
	int** arr = new int* [row];
	for (int i = 0; i < row; i++)
	{
		arr[i] = new int[col];
	}
	return arr;
}
int main()
{
	int** arr = NewArr2D(2, 3);
	int cnt = 0;
    //initialization
	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			arr[i][j] = cnt++;
		}
	}
    //Print
	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			cout << arr[i][j] << " ";
		}
		cout << endl;
	}
	delete[] arr;
}


​

You can see that the printing is successful!

 

(3) Memory application dynamic structure

It is roughly the same as the dynamic memory application of an array.

struct A
{
	char* name;
	int age;
	void print();
};
void A::print()
{
	cout << name << " " << age << endl;
}
int main()
{
	A* pA1 = new A;
	pA1->name = new char[18];
	strcpy_s(pA1->name, 18,"Blue ");
	pA1->age = 18;
	pA1->print();
	delete pA1->name;
	delete[] pA1;
}

We can see that if there is a pointer in the structure of the application, it can only be used after secondary application, and the order of application and release is opposite, that is, when applying for memory, it is "from large to small", and when releasing memory, it is "from small to large". If the order is reversed, repeated release will occur.

III Memory pool

What I want to introduce here is how to carry out the comprehensive management of memory.

We know that the dynamically applied memory in C language is uniformly stored in the heap area, while the memory from "new" in C + + is in the "free storage area". How to understand the word "freedom"?

new(Start of memory request)

It can be seen that the so-called freedom means that you can freely choose where to store the dynamically applied memory to analyze the following codes:

void textMemory()
{
	char* memorySum = new char[1024];
	int* pSum = new(memorySum) int[3]{ 1,2,3 };
	char* pChar = new(memorySum + sizeof(int) * 3) char[20]{ "I Love C++" };
	delete[] memorySum;
}

First, we applied for a large buffer "memorySum". Then on this unused memory, we will start from the first address of "memorySum", take the next 12 bytes of space to the pSum array, and then take the next 20 bytes of space to "pChar". Then we just need to release this buffer space, This is the integrated memory management.

IV string type

1. Create a string

The header file < string > needs to be included here. Note that it is similar to < string in C language h> It's different.

int main()
{
	//If there is no using namespace std, it needs to be expressed as follows:
	std::string str;
	//Not initialized
	string str1;
	str1 = "I Love C++";
	//initialization
	string str2 = "I Love C++";
	//Create from another string
	string str3 = str1;
	string str4(str2);
}

2. Basic operation of string

(1) Assignment copy

Using the equal sign directly is very convenient!

int main()
{
	string str1 = "one";
	string str2 = "two";
	string str3 = str1;
}

(2) Connect

There are two methods, one is to directly use "+" and the other is to call functions.

int main()
{
	string str1 = "one";
	string str2 = "two";
	string str3 = str1 + str2;
	string str4 = str1.append(str2);
}

(3) Compare

There are still two ways, one is direct comparison, and the other is to use functions.

int main()
{
	string str1 = "one";
	string str2 = "two";
	if (str1 > str2)
	{
		cout << "str1 Relatively large"<<endl;
	}
	else if (str1 < str2)
	{
		cout << "str2 Relatively large"<<endl;
	}
	else
	{
		cout << "The same big as that"<<endl;
	}
	if (str1.compare(str2) == 1)
	{
		cout << "str1 Relatively large" << endl;
	}
	else if (str1.compare(str2) == -1)
	{
		cout << "str2 Relatively large" << endl;
	}
	else
	{
		cout << "The same big as that" << endl;
	}
}

3. What is the difference between C language string and C + + string

String is actually a custom type in C + +, and string does not record '\ 0', which is used as the end of the string. The string of C + + is not the char * type we understand, so the character processing function in C language cannot be used. If you want to use it, you must first convert the string into char * type. The following two methods can be implemented:

int main()
{
	string str1 = "one";
	const char* str = str1.c_str();
	const char* strr = str1.data();
}

This method is very common when C + + is used to encapsulate the graphical interface.

4. Other interesting operations

Here's the code. Play with it yourself. Hahaha.

int main()
{
	string str1 = "one";
	//empty, size function
	if (str1.empty()) cout << "Empty";
	else cout << "Not empty";
	cout << endl << str1.size();
	//to_ The string function is a bit like c# ToString
	string str2 = to_string(123);
	//C language can use atoi function to brush questions
}

Finally, the links to find these functions are attached to facilitate the search~

basic_string classhttps://docs.microsoft.com/zh-cn/cpp/standard-library/basic-string-class?view=msvc-170 Today's finishing is here, continue to work hard!!!

Keywords: C++

Added by keakathleen on Sun, 20 Feb 2022 17:47:34 +0200