preface

C and C++ are the primary language foundation for learning audio and video technology, so it is necessary to learn and review the previous learning of C++ language foundation.

Here IDE and environment configuration in the previous C language review article has been said, or use CLion this software, without saying a word, directly start learning.

The body of the

C++, as a language with a wider range of uses and more complete functions, has a deep knowledge depth. Therefore, I will review and learn some basic knowledge points here, and supplement them when encountering difficulties in practical projects.

hello world

After creating a C++ project, print hello world as follows:

#include <iostream> // namespace to tell the compiler to use STD namespace using namespace STD; int main() { printf("Hello, World! \n"); Cout << "Hello, World!" << endl; return 0; }Copy the code

The print is:

From this simple program we can see that entry functions and return values are the same as in C, but there is a concept of namespaces. What is a namespace?

To put it bluntly, C++ does not have package restrictions like Java, so the need to distinguish between namespaces is to use namespaces.

And then there’s the cout function here, which is basically short for STD ::cout, a function in the STD namespace that normalizes output to the screen, just like printf, where << is called the stream insertion operator, where endl is a newline, or if you use \n, There’s nothing more to say here, but it simplifies printf.

The keyword

There are a lot of C++ keywords, we can not and learn the C language, all listed again to see, here is a look at some commonly used, useful to other supplementary.

Have to say C++ is really complicated, this is only a part of the keyword, let a person see dizzy, but not afraid, take your time first, there is a supplement and then fill up.

Variable scope

The basic data types are similar to the basic data types in C, so let’s talk about variable scope.

  • Variables declared inside a function or a code block are called local variables.

  • Variables declared in the definition of function parameters are called formal parameters.

  • Variables declared outside all functions are called global variables.

Define constants

Leaving aside the concept of what a constant is, here are two common ways to define a constant:

  • Use the #define preprocessor.

  • Use the const keyword.

Look directly at the following code:

#include <iostream> // This must include <string> using namespace STD; #define NAME "zyh" const int AGE = 20; const string COMPANY = "WY"; int main() { cout << NAME << endl; cout << "age : " << AGE << endl; cout << "company : " << COMPANY << endl; return 0; }Copy the code

Print result:

Note that cout output must include if the output is a string. Otherwise, only a char array can be used to represent the string output.

string

In front of learning C, we use String is the use of character array to complete, and the Java String class is simply not comparable, too inconvenient, so in C++ introduced String class, but can still adapt to the C-style String, directly look at the code:

using namespace std; Int main() {//C greet[6] = "Hello"; char *greet1 = "Hello"; char greet2[] = "Hello"; //C++ uses string. Greet3 = "Hello"; cout << greet << endl; cout << greet1 << endl; cout << greet2 << endl; cout << greet3 << endl; return 0; }Copy the code

In C, string manipulation functions such as strcpy and strcat can be used. In addition, there are also some string functions, which are very similar to some Java methods. Such as append, length methods, etc.

Pointer to the

We have learned about Pointers in the previous article in C, C++ Pointers are similar, the role of Pointers are mainly two points:

  • Simplify some tasks by using Pointers
  • Dynamic memory allocation, when dynamic memory allocation, must use Pointers

Pointer definition and use and C language exactly the same, including the definition and take the address symbol & and get the pointer to the value * here will not say, not clear can review the previous C language pointer.

reference

A reference is similar to a pointer but not a pointer. It is equivalent to an alias for a variable name.

The notion that a reference can’t be null and must be initialized feels a bit redundant. After all, we have Pointers in C++, and references are basic in Java, thinking of reference types. So there is still a distinction to be made here, especially when defined with &. Here’s a quick look:

using namespace std; Int main() {// declare a variable int a = 10,b = 20; // declare the reference variable int & I = a; int &j = b; cout << "a ==" << a << "\t &i ==" << i <<endl; cout << "b ==" << b << "\t &j ==" << j <<endl; // Change the value of the variable, the reference also changes a = 5,b = 6; cout << "a ==" << a << "\t &i ==" << i <<endl; cout << "b ==" << b << "\t &j ==" << j <<endl; return 0; }Copy the code

A and I refer to the same memory area, but it can be used as a variable, and its address is the same.

Function arguments are of reference type

When using value pass, the value will be copied. Function execution does not affect the value passed in. Pointer is an address, so function execution will definitely change.

A reference is just an alias for a variable, so a parameter type is a reference. It has the same effect as a pointer.

using namespace std; void swap(int& x,int& y); void swap1(int x,int y); int main() { int a = 100,b = 200; Cout << "a =" << a << "b =" << b << endl; swap(a,b); Cout << "a =" << a << "b =" << b << endl; swap1(a,b); Cout << "a =" << a << "b =" << b << endl; return 0; Void swap(int &x,int &y){int temp; temp = x; x = y; y = temp; Void swap1(int x,int y){int temp; temp = x; x = y; y = temp; }Copy the code

There are two kinds of exchange, one is to pass the value and the other is to reference, print as follows:

You will find that using references also causes the original value to change.

Classes and objects

Finally to C++, which is object oriented, familiar with the Java language for object oriented is certainly handy, here is to see how C++ is object oriented.

Again, look directly at the code:

#ifndef CPLUSTEST_PERSON_H #define CPLUSTEST_PERSON_H class Person{// public attribute: Person(); // Empty argument constructor ~Person(); // destructor Person(char *name,int age); // Char *name; int age; Void setName(char *name); char *getName(); void setAge(int age); int getAge(); }; #endif //CPLUSTEST_PERSON_HCopy the code

This is the person. H file, which is used to define functions, classes, etc. Headers are also used to define functions, classes, etc.

#include <iostream> #include "person.h" using namespace std; Person::Person(char *name, int age) { this -> name = name; this -> age = age; } Person::~Person() {cout << "Person destroy "<< endl; } Person::Person() {cout << "execute the Person empty constructor" << endl; } void Person::setAge(int age) { this -> age = age; } void Person::setName(char *name) { this -> name = name; } int Person::getAge() { return this -> age; } char *Person::getName() { return this -> name; }Copy the code

This is the person. The CPP file, import front header files, here is implemented, there is a big difference and Java class definition, common definitions in Java or kotlin directly after the implementation, not separate two places, then where is called:

Person personTemp; Person personTemp; Person personTemp; Person personTemp; Person personTemp; PersonTemp. Elegantly-named setName (" zhang "); personTemp.setAge(10); cout << personTemp.getName() << "\t" << personTemp.getAge() << endl; Person * Person = new Person("zyh",18); cout << person -> name << "\t" << person->getAge() << endl; Delete person; return 0; }Copy the code

In Java, an object is null if the constructor is not called, and its methods cannot be called. However, in C++, it is different. At the same time, using the new operator to create an object, you need to manually delete the memory, Java is automatic GC collection, also more trouble.

Here is a brief summary, and then in detail:

C++ class member functions

What is a class member function needless to say, learned object-oriented language all know, here mainly say class member function has two ways of definition.

One is to declare it directly in a class, which is the way the Java language does it, and the other is to declare it in a class somewhere else, which is the way C++ recommends it. For example, the following class Box is declared in a header file:

#ifndef CPLUSTEST_BOX_H #define CPLUSTEST_BOX_H #define CPLUSTEST_BOX_H // Length double width; // width double height; Double getVolume(){return length * width * height; } double getVolume2(); / / volume}; #endif //CPLUSTEST_BOX_HCopy the code

There are two member functions, getVolume2, which we define in a.cpp file:

#include "box.h"

double Box::getVolume2() {
    return length * width * height * 2;
}
Copy the code

You can do either of the above. Member functions defined in a class are declared inline. Where :: is called the range resolution operator.

C++ constructor and destructor

We’re all pretty familiar with constructors, but the only thing we’re going to talk about here is using an initializer list to initialize a field, which is what the name means.

If kotlin’s data class automatically does that for me. If the parameter has the val/var modifier, all other classes are assigned to it in the init block. C++ has a different way of writing it, Here it is:

#ifndef CPLUSTEST_BOX_H #define CPLUSTEST_BOX_H #define CPLUSTEST_BOX_H // Length double width; // width double height; Double getVolume(){return length * width * height; } double getVolume2(); // volume // custom constructor Box(double len); }; #endif //CPLUSTEST_BOX_HCopy the code

The Box definition here adds a parameter constructor, and then in the place defined:

Box::Box(double len) : length(len) {STD ::cout << "constructor input len" << endl; }Copy the code

This is the one that comes directly after the function: assign a field, which is a novel way to write it.

There is also the destructor, which, like the no-argument constructor, the compiler will add if not written. The destructor is the same as the default constructor but with multiple ~ s. You can use the destructor to exit the program, close resources, and so on.

Once again, the Person class defines the destructor, and then we use two separate objects to look at printing:

Person personTemp; Person personTemp; Person personTemp; Person personTemp; Person personTemp; PersonTemp. Elegantly-named setName (" zhang "); personTemp.setAge(10); cout << personTemp.getName() << "\t" << personTemp.getAge() << endl; Person * Person = new Person("zyh",18); cout << person -> name << "\t" << person->getAge() << endl; Delete person; return 0; }Copy the code

Print the following:

You’ll see that both automatically reclaimed objects and manually deleted objects call the destructor when the object is released. Of course, objects created using the new keyword will not be released without a call to DELETE.

C++ copy constructor

What is the copy constructor, this is actually very simple, is to use A class before creating objects to create A new object, for example, I have A Box A, now want to have A Box, B to B and A content, then consider, if is A Java code B, A2 references refer to the same object, it’s not too conforms to the requirements, So the copy function will be called, and it will definitely create a new object.

In C++, the concept of copy constructors comes straight out of the box to make copying easier. In C++, if the member of A class is A pointer variable, think about it carefully, copy the pointer of A directly into the pointer variable of B, so that the variable in A, B2 objects are the same address, then it will affect each other, certainly not.

So even though there is a copy constructor by default, the copy constructor is overridden when a class member variable is a pointer.

#ifndef CPLUSTEST_LINE_H #define CPLUSTEST_LINE_H class Line{ public: int getLength(); Line(int len); // Copy constructor must define Line(const Line &obj); ~Line(); Private: // This is a pointer variable int * PTR; }; #endif //CPLUSTEST_LINE_HCopy the code

For example, when a member variable in the code above has a pointer variable,

#include "line.h" #include <iostream> using namespace std; Line::Line(int len) {cout << "call constructor" << endl; PTR = new int; PTR = new int; Len * PTR = len; } Line::Line(const Line &obj) {cout << "call copy constructor" << endl; PTR = new int; PTR = new int; * PTR = *obj. PTR; } Line::~Line() {cout << "free memory" << endl; delete prt; }Copy the code

One problem I can see from the above code is that C++ has a shallow copy and a deep copy problem. Just like Java, if it is such a pointer variable, memory needs to be reallocated.

The above example shows that the copy constructor is called when an object needs to be initialized by another object.

C++ friend functions

This concept doesn’t really exist in Java, but it’s easy to understand what it means. A friend is a friend. A friend function is declared in a class, but defined outside the class, and can be used to access private and protected members of the class.

The friend function is not a member of the class, but it can access the private variables of the class.

Let’s look at a code example:

#ifndef CPLUSTEST_BOX_H #define CPLUSTEST_BOX_H class Box{ double width; Public: friend void printWidth(Box Box); // Declare a friend function void setWidth(double width); }; #endif //CPLUSTEST_BOX_HCopy the code

Here we declare a friend function to get private variables,

#include <iostream>
#include "box.h"

using namespace std;

void Box::setWidth(double width) {
    this->width = width;
}

void printWidth(Box box){
    cout << "width = " << box.width << endl;
}
Copy the code

Friend functions cannot be called with Box:: because they are not in Box.

using namespace std;

int main() {

    Box *box = new Box();
    box->setWidth(10);
    printWidth(*box);
    delete box;
}
Copy the code

The width property does not have any get methods, but can be accessed via friends. The C++ design is in place.

C++ inline functions

The concept of inline functions was first introduced in kotlin, and since the concept is not present in Java, it is now in C++ that kotlin continues to improve on the strengths of other languages.

Inlining is literally inlining. If a function is defined to be inlined, the compiler will place a copy of the function’s code wherever the function is called at compile time, just for efficiency.

For normal functions, they are replaced on the stack at run time, but for inline functions, they are copied at compile time, which is a way to trade space for time. Therefore, inline functions are usually no more than 10 lines.

C + + inheritance

Object oriented, inheritance is not a consideration, familiar with Java are very well understood, here will not say.

The difference is that C++ can inherit, that is, can inherit multiple parent classes, this in Java only allowed to inherit a parent class, implement multiple interfaces.

Dynamic memory

In fact, this is very simple, similar to Java memory allocation, in C++ function execution is also in and out of the stack, so the function defined variables will occupy the stack memory, will be released after the function execution.

When using the new keyword, memory can be allocated dynamically. The memory is in the heap and is freed using delete.

For pointer variables, we can use a pointer of built-in type new, which we have already described in copying functions.

The namespace

This is nothing to say, is a bunch of variables and functions divided into a block, this block to give a name.

conclusion

In fact, the C++ part is in C above the concept of object oriented, oriented to familiar with Java is also very easy to understand, so this article is a simple review, such as later practical problems to supplement.