[C++] Keywords, classes and objects, etc. - Meow Meow Wants to Eat C Quack 2

0a4bde25e142427e9fb8f47ab1aca386.png

I hope you are happy, I hope you are healthy, I hope you are happy, I hope you like it!

Finally, follow meow, follow meow, follow meow, you will see more interesting blogs! ! !

Meow meow meow, you are really important to me!

Table of contents

Preface

auto keyword (C++11)

Range-based for loop (C++11)

Pointer null value nullptr (C++11)

Process-oriented and object-oriented understanding

Introduction of classes

Class definition

Two ways to define classes:

Class access qualifier

encapsulation

class scope

Summarize


Preface

Today we summarize the keywords, Meow Meow Team, rush rush rush! ! !

Today is also a day to miss you, meow~


auto keyword (C++11)

In C++11, the standards committee gave auto a new meaning:auto is no longer a storage type indicator, but as a new type indicator. Instructs the compiler that variables declared with auto must be deduced by the compiler at compile time.

Note: When using auto to define a variable, it must be initialized. During the compilation phase, the compiler needs to deduce auto based on the initialization expression. Actual type. Therefore, auto is not a "type" declaration, but a "placeholder" for type declaration. The compiler will replace auto with the actual type of the variable during compilation.

autoNote:

  • autoUse with pointers and references

       用autoWhen the statement finger type, useautoauto*Not responsible for any division, howeverautoStatement citation type time Please join

	int main()
	{
	int x = 10;
	auto a = &x;
	auto* b = &x;
	auto& c = x; 7
	cout << typeid(a).name() << endl;
	cout << typeid(b).name() << endl;
	cout << typeid(c).name() << endl; 11
	*a = 20;
	*b = 30;
    c = 40;

	return 0;
	}

  • Define multiple variables on the same line

        When multiple variables are declared on the same line, these variables must be of the same type, otherwise the compiler will report an error, because the compiler actually only operates on the first type of Derivation, and then defining other variables with the derived type.

	void TestAuto()
	{
	auto a = 1, b = 2;
	auto c = 3, d = 4.0; // 该行代码会编译失败,因为c和d的初始化表达式类型不同
	}
  • auto cannot be used as a function parameter
  • auto cannot be used directly to declare arrays
  • To avoid confusion with auto in C++98, C++11 only retains the use of auto as a type designator.

Basic 范围的forcirculation(C++11)

For aranged collection, it is redundant for the programmer to specify the range of the loop, and sometimes it is easy to make mistakes. mistake. Therefore, range-based for loops were introduced in C++11. forThe parentheses after the loop are composed of colons:< a i=7>” is divided into two parts: the first part is the variable within the range used for iteration, the second part represents the range being iterated a>.

void TestFor()
{
int array[] = { 1, 2, 3, 4, 5 }; for(auto& e : array)
e *= 2;
for(auto e : array)
cout << e << " ";

return 0;
}

Note: Similar to a normal loop, you can use continue to end this loop, or you can use break to jump out of the entire loop.

范围foruse

The range of for loop iteration must be certain

For an array, it is the range of the first element and the last element in the array;

For classes, begin and end methods should be provided. Begin and end are the scope of the for loop iteration.

Note: There is a problem with the following code because the scope of for is uncertain

	void TestFor(int array[])
	{
	for(auto& e : array)
	cout<< e <<endl;
	}

Pointer null valuenullptr(C++11)

When declaring a variable, it is best to give the variable an appropriate initial value, otherwise unpredictable errors may occur, such as uninitialized pointers.

NULL is actually a macro.

In C++98, the literal constant 0 can be either an integer number or an untyped pointer (void*) constant, but the compiler treats it as an integer constant by default. If you want to treat it as To use it in pointer mode, it must be cast (void *).

Notice:

  1. When usingnullptr to represent the pointer null value, there is no need to include the header file, becausenullptr< /span>. introduced as a new keywordC++11is
  2. In order to improve the robustness of the code, it is recommended to usenullptr when subsequently expressing the null value of a pointer.
  3. currentC++11in,sizeof(nullptr)  Give  sizeof((void*)0)Possessive lexical number homology.

Process-oriented and object-oriented understanding

C language isprocess-oriented, focused It is a process that analyzes the steps to solve the problem and solves the problem step by step through function calls.

C++ isbased on object-oriented and focused on It isobject, which splits one thing into different objects and is completed by the interaction between objects.


Introduction of classes

Only variables can be defined in the C language structure. In C++, not only variables but also functions can be defined in the structure. 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 C language structure can be changed to class, give it a try!


Class definition

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

class is the keyword that defines the class, ClassName is the name of the class, {} is the main body of the class, please note The semicolon after 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 is called attribute of class or member variable; functionsin a class are called methods of the classor Member functions.

Two ways to define classes:
  1. Declarations and definitions are all placed in the class body. Please note: if a member function is defined in the class, the compiler may Treated asinline function.

  1. Declarations and definitions are all placed in the class body. Please note: if a member function is defined in the class, the compiler may Treated asinline function.
  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 member function name

Miao Miao suggested: prefers the second method.

Note: In order to facilitate the demonstration of using method one to define classes in class, everyone should try to use the second method in subsequent work.

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

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

// 或者这样
class Date
{
public:
void Init(int year)
{
mYear = year;
}
private:
int mYear;
};


Class access qualifier

[Access Qualifier Description]

  1. Members modified by public can be directly accessed outside the class
  2. The default access rights of class are private and struct is public (because struct must be compatible with C)
  3. If there is no access qualifier later, the scope ends at }, which is the end of the class.
  4. The access scope begins at the occurrence of this access qualifier and ends at the occurrence of the next access qualifier.
  5. Protected and private modified members cannot be directly accessed outside the class (protected and private are similar here)

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

[Interview questions]

Problem:C++mediumstructsum is different? class

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. The class defined by class is the same as . The difference is that the default access permission of the class defined by struct is public, and the default access permission of the class defined by class is private. Note: There are also differences between struct and class in inheritance and template parameter list positions.


encapsulation

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

Encapsulation: Organically combine data and methods of operating data, hide the properties and implementation details of the object, and only expose the interface 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. But in fact, the real work of the computer is the CPU, graphics card, memory and other hardware components.

For computer users, there is no need to worry about the internal core components, such as how the circuits on the motherboard are laid out, how the CPU is designed internally, etc. Users only need to know how to turn on the computer and how to communicate with the computer through the keyboard and mouse. Just interact. ThereforeWhen computer manufacturers leave the factory, they put a shell on the outside to hide the internal implementation details, and only provide power switches, mouse and keyboard jacks to the outside so that users can interact with the computer. Just.

To implement encapsulation in C++ language, you can organically combine data and methods of operating data through classes, hide the internal implementation details of objects through access permissions, and control which methods can be used in Used directly outside the class.


class scope

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

Summarize

That’s it for today! Meow Meow will work hard to update, please support me.


I hope you are happy, I hope you are healthy, I hope you are happy, I hope you like it!

Finally, follow meow, follow meow, follow meow, you will see more interesting blogs! ! !

Meow meow meow, you are really important to me!

530b9a7e0a634b81bfe44228d5ff8023.png

Guess you like

Origin blog.csdn.net/ormstq/article/details/134127672