[Things about C++] First introduction to C++ namespace, input, output and default functions in C++

Insert image description here

Junxi_'s personal homepage

No matter how far you go, never forget your original intention when you started the journey

C/C++ game development

Hello, Mina-san, this is Junxi_. The preliminary update of data structure and algorithm is completed. Let’s continue to expand our knowledge. Today we will start from understanding C++ to teach you C++. I have read a set of books before. It's called "Those Things About the Ming Dynasty" and it makes the otherwise boring history lively and interesting. As a low-level language, C++ is undoubtedly abstract and difficult. I hope to work hard to make abstract and complex knowledge vivid and easy to understand. Therefore, our series of blogs explaining C++ is called "Things About C++"

Pilot: What is C++?

Speaking of C++, many of us have heard of its top name. C++ has also occupied the top five programming languages ​​​​used by programmers on the market all year round, which is enough to illustrate its importance and recognition. So in the end, what What about C++?
Insert image description here

  • C language isstructured and modular Language, suitable for processing smaller-scale programs. For complex problems, large-scale programs that require a high degree of abstraction and modeling, C language is not suitable. In order to solve the software crisis, in the 1980s, the computer industry proposed the idea of ​​OOP (object oriented programming) in the 1980s. >, supporting object-oriented programming languages came into being.



    Insert image description here

  • In 1982, Dr. Bjarne Stroustrup (the grandfather of C++) introduced and expanded the concept of object-oriented on the basis of C language and invented A new programming language. In order to express the origin relationship between the language and the C language, it was named C++. Therefore:C++ is based on C language. It can not only perform procedural programming of C language, but also perform object-based programming characterized by abstract data types. It can also Do object-oriented programming

In the final analysis, our ancestor discovered many shortcomings and defects of C language when he used it. This made him very unhappy when using it, so he started to develop it on the basis of C language. A new language, C++, has its own say. He has made up for the shortcomings of C and those things that make people uncomfortable when using it in his own language. C++ came into being. Later, after continuous development and advancement, With the continuous introduction of new standards and features, we have arrived at the current C++ in our computers!

Application of C++ in the work field

  • 1. Operating system and large-scale system software development
    Almost all operating systems are written in C/C++, and many large-scale software are almost written in C++, such as: a>
    Photoshop, Office, JVM (Java Virtual Machine), etc. The reason is that they have high performance and can directly control the hardware.
  • 2. Server-side development
    Backend development: mainly focusing on the processing of business logic, that is, responding to front-end requests and back-end responses, which is now the mainstream method< a i=2> uses Java, but the involution is serious. Large manufacturers may have C++ background development, mainly doing some basic components, middleware, cache, distributed storage, etc. Server-side development is more extensive than back-end development, including back-end development, which generally has relatively high real-time requirements, such as game servers, streaming media servers, network communications, etc., all developed in C++.


  • 3. Game development
    Almost all games on the PC platform are written in C++, such as: World of Warcraft, Legend, CS, Kart Racing, etc., on the market
    Quite a few game engines are developed based on C++, such as: Cocos2d, Unreal 4, DirectX, etc. The field of three-dimensional games
    has a very large amount of calculations, and the underlying mathematics are all matrix transformations. If you want to have beautiful graphics, rich content, and real-time game performance
    , these advanced There is no doubt that the only choice for difficulty requirements is the C++ language. Relatively well-known manufacturers: Tencent, NetEase, Perfect World, Giant Network, etc.
  • 4. Embedded and Internet of Things fields
    Embedded: It means embedding a main control board with computing power inside a machine or electronic device to control these , Baidu, Meituan, etc. all have hardware-related business units. With the popularization of 5G, the Internet of Things (i.e., the Internet of Everything) has also become an emerging force, such as: Alibaba lot, Tencent lot, Jingdong Factories; manufacturers with their own terminal business such as DJI, Hikvision, Dahua, and CVTE; as well as traditional home appliance industries such as Haier, Hisense, and Gree. Some well-known manufacturers, such as: mobile phone manufacturers represented by Huawei, vivo, oppo, and Xiaomi; chip manufacturers represented by Unisoc and Espressif Systems Common positions include: embedded development engineer, driver development engineer, system development engineer, Linux development engineer, firmware development engineer, etc. bare metal Development), in addition to microcontroller development, embedded development also includes development on the SOC chip, system level, driver level, application and middleware level. When it comes to embedded development, what everyone can think of most is microcontroller development (that is, carried out on 8-bit, 16-bit or 32-bit microcontroller products or
    device. For example: smart bracelets, cameras, sweeping robots, smart speakers, etc.









  • 5. Digital image processing
    Digital image processing involves a large number of mathematical matrix operations, which requires relatively high CPU computing power. The main image processing
    Algorithm libraries and open source libraries are all written in C/C++, such as: OpenCV, OpenGL, etc. The famous Photoshop
    is written in C++.
  • 6. Artificial Intelligence
    When it comes to artificial intelligence, the first thing that comes to mind is python. People think that learning artificial intelligence requires learning python. This
    This is a misunderstanding. There are many libraries in python. You can use python to quickly build a neural network, fill in the parameters and import the data, and then you can start training the model. But the core behind artificial intelligence, such as the deep learning algorithm, is still written in C++.
  • 7. Distributed applications
    With the rise of the mobile Internet in recent years, the data volume of each application has continued to increase; the back-end architecture must continue to improve performance and concurrency
    Only ability can cope with the advent of the big information age. In the distributed field, many distributed frameworks, file systems, intermediate components, etc.
    are all developed in C++. Several heavyweight components of the Hadoop ecosystem that have a great impact on distributed computing: HDFS, zookeeper, HBase, etc. are also based on GFS, Chubby, and BigTable implemented by Google in C++. Including the distributed computing framework MapReduce, Google first implemented it in C++, and then there was an open source Java version.

In addition to the above fields, scientific computing, browsers, streaming media development, network software, etc. are all scenarios where C++ is more suitable.
As an evergreen tree of old language, C++ has always occupied the top five programming languages, and it definitely has its value

How to learn C++?

  • Here is a set of tips for mastering C++ in 21 days for your reference:
    Insert image description here
  • One of the disadvantages of C++ is that it is more complex than many languages ​​and is difficult to learn and master. Therefore, it is basically impossible to say that you are proficient in it in a short period of time. It is even said that there are very few big guys who currently dare to claim to be proficient in C++, except for those who develop compilers and new languages.
  • Therefore, here, my advice to you is not to regard "proficient in C++" as a one-year goal. You should regard learning the language as a continuous process, and at the same time apply the language in specific application situations. Whatever you want to achieve, For challenging things, perseverance is your best choice! !

Okay, after talking so much about C++, are you ready to officially start learning C++? Whether you are ready or not, don’t think too much. Now, Just Do it. You will not make progress if you don’t do it. Take a deep breath and start our formal C++ learning! !


1. Namespace

  • I don’t know if you have encountered this situation. When you define a function or variable in the C language, the editor prompts you that the function or variable already exists.
    Insert image description here
  • In the C language, such a naming problem cannot be solved. In order to solve the problem of naming conflicts, the concept of namespace is proposed in C++.

What is a namespace

  • In C/C++, there are a large number of variables, functions and classes to be learned later, and the names of these variables, functions and classes will all exist
    in their global role domain, may cause many conflicts. The purpose of using a namespace is to localize the name of the identifier,
    to avoid naming conflicts or name pollution. The namespace keyword appears to address this problem

Namespace definition

  • To define a namespace, you need to use the namespace keyword, followed by the name of the namespace, and then followed by a pair of {}. {}
    are the members of the namespace. .
#include<iostream>
namespace junxi
{
    
    
    int rand = 10;
}
int main()
{
    
    
    printf("%d\n", rand);//在这里这是错误的用法,别急,在使用命名空间是会讲
    return 0;
}

In future work and project development, many people often collaborate. In order to prevent conflicts with other namespaces, it is recommended that the namespace here be written as the abbreviation of your own name. Of course, other names will also work. It doesn’t matter if you recognize it yourself. question.

  • In addition to variables, you can also define functions, structures, etc. in the defined namespace.
    In addition, the namespace supports nesting, which means that in naming Define a namespace in the space.
    Finally, multiple namespaces with the same name are allowed to exist in the same project, and the compiler will eventually combine them into the same namespace. In actual development, this method is not commonly used. .
namespace junxi
{
    
    
    int rand = 10;

    int Add(int x, int y)
    {
    
    
        return x + y;
    }
    
    namespace Junxi//嵌套
    {
    
    
       
        
    }
    struct Node
    {
    
    
        struct Node* next;
        int val;
    };

}
//同一工程中相同的命名空间最后会合并
namespace junxi
{
    
    
    int a = 0;
    int b = 0;
}
int main()
{
    
    
    printf("%d\n", rand);
    return 0;
}
  • Notice:
  • 1. Never write the main function in a namespace. We know that every project needs a main function. If you write the main function in a namespace and do not use it, there will be no main function in the project. Functional! !
  • 2. A namespace defines a new scope, and all content in the namespace is limited to this namespace.

Use of namespaces

  • Looking back at the code we just wrote, I said above that there was an error when printing rand.
    Insert image description here
  • When we print, random numbers appear. Why is this?
  • Because rand is in the namespace, if we want to use a member of the namespace, we have to do the following:

Three ways to use namespaces

  • 1.Add namespace name and scope qualifier
int main()
{
    
    
    printf("%d\n", junxi::rand);
    return 0;
}

Insert image description here

  • 2.Use using to introduce a member of the namespace
using junxi::a;
int main()
{
    
    
    printf("%d\n", a);
    return 0;
}
  • 3.Use using namespace namespace name introduction
using namespace junxi;
int main()
{
    
    
    printf("%d\n", a);
    return 0;
}
  • If you observe carefully, you will find that rand is not printed when I use the two namespaces 2 and 3. Why is this?
  • Notice:
  • This does not mean that the problem of function redefinition in C language has been completely solved in C++. When we encounter the following situations, errors will still be reported:
  • The first situation
namespace junxi
{
    
    
    int rand = 10;

    int Add(int x, int y)
    {
    
    
        return x + y;
    }
    
    namespace Junxi
    {
    
    
       
        
    }
    struct Node
    {
    
    
        struct Node* next;
        int val;
    };

}

using junxi::rand;
int main()
{
    
    
    printf("%d\n", rand);
    return 0;
}

Insert image description here

  • Second case
using namespace junxi;
int main()
{
    
    
    printf("%d\n", rand);
    return 0;
}

Insert image description here

  • At this time, although you quoted the namespace or pointed out the members in the corresponding namespace, because the rand function exists in the library, you did not clearly indicate which one to print when printing, and the compiler was unable to compile the unclear code, therefore, if you encounter the above situation in actual programming development, it is recommended to use the first method of using namespace members! !

2. Input and output in C++

  • One input for many of us when learning programming languages ​​is often "hello world". So, how do we use C++ to greet this wonderful world?
#include<iostream>
// std是C++标准库的命名空间名,C++将标准库的定义实现都放到这个命名空间中(类似于我们C语言中的stdio)
using namespace std;
int main()
{
    
    
cout<<"Hello world!!!"<<endl;//输出
return 0;
}
  • Specific instructions
  • 1. Use cout standard output object (console) and cin standard input object (keyboard) ), you must include the < iostream >header file
    and use std according to the namespace usage.
  • 2. cout and cin are global stream objects, endl is a special C++ symbol, indicating newline output, they are included in the package <
    iostream >In the header file.
  • 3. << is the stream insertion operator, >> is the stream extraction operator.
  • 4. It is more convenient to use C++ for input and output. There is no need to manually control the format like printf/scanf input and output. C++ input and output can automatically identify variable types
#include <iostream>
using namespace std;
int main()
{
    
    
    int a;
    double b;
    char c;
    // 可以自动识别变量的类型
    cin >> a;
    cin >> b >> c;//输入数回车结束 先输入到b中,再输入到c中
    cout << a << endl;
    cout << b << " " << c << endl;//从左到右打印
    return 0;
}
  • There are so many << and >> that many beginners may not be able to distinguish, so I will teach you a little tip that can be quickly remembered.
  • <<The stream insertion operator, you think of it as a stream of water, means that the content you want to input flows into cout, and cout will help you output the content to the console, that is, printing!
  • >> Stream extraction operator, after cin reads the data from the keyboard, it flows out >> to where you want it to go, right? It’s input!
  • In other words, looking at the directions of these two operators can easily help us distinguish whether they are input or output.
  • Many people may have this question after seeing this. In daily use, how to use cout and cin to control the integer format or floating point output precision?

Of course, cout and cin can help us achieve this goal. For beginners, it is more troublesome to use cout and cin to control input and output, so we will not study here. If you really encounter similar needs during use, don't forget that C++ is compatible with C! Can we use C method to achieve it?


3. Default function

  • What is the default function?
  • The default parameter is to specify a default value for the function parameters when declaring or defining the function. When calling this function, if no actual parameter is specified, the default value of the formal parameter will be used, otherwise the specified actual parameter will be used.
void Func(int a = 0)
{
    
    
    cout << a << endl;
}
int main()
{
    
    
    Func(); // 没有传参时,使用参数的默认值
    Func(10); // 传参时,使用指定的实参
    return 0;
}

Insert image description here

Classification of default functions

  • In the above example, our function has only one parameter passed in. When multiple parameters are passed in, our default function will have different types.
  • All default functions
void Func(int a = 10, int b = 20, int c = 30)
{
    
    
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
  • That is, every function passed in a parameter has a default value, which we regard as a full default function.

  • semi-default function

void Func(int a, int b = 10, int c = 20)
{
    
    
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}

Notice:

1. Semi-default parameters must be given sequentially from right to left, and cannot be given at intervals.
2. Default parameters cannot appear at the same time in the function declaration and definition. Often It appears in the declaration
3. The default value must be a constant or a global variable
4. The C language does not support default functions (the compiler does not support it)< /span>

  • Let me explain the first two points mentioned above.
  • The first point is why it must be given from left to right without intervals?
void Func(int c, int a = 0, int d )
{
    
    
    cout << c << endl;
    cout << a << endl;
    cout << d << endl;
}
int main()
{
    
    
    
    Func(10); // 传参时,使用指定的实参
    return 0;
}
  • If the above situation occurs and we only pass in one parameter, then, should this parameter be assigned to c or d? Only you know, but our compiler does not know, so the values ​​of the default parameters must be set in order
  • Second point, why can't it appear in the declaration and definition of the function at the same time?
//a.h 在头文件中
void Func(int a = 10);
// a.cpp //具体实现时的定义
void Func(int a = 20)
{
    
    }
  • If the above situation occurs and the default parameters you give are different when declaring and defining, then who will the compiler use as the criterion when running the program? At the same time, normally speaking, you cannot just give it in the definition, because if you only reference its corresponding header file when using a function, there will be no default parameters in the declaration. When you actually use the function There are no default parameters. Therefore, in our daily use, it is best to use default functions in declarations.

Summarize

  • Okay, that’s it for today! Today we mainly introduce the concept of namespace, input, output and default functions in C++ and the precautions. As the saying goes, you can’t eat hot tofu in a hurry. As I said before, learning C++ is not something that happens overnight, it is only continuous accumulation and repetition. Only practice can help you reach the peak of C++.

  • If you have any questions or doubts about the content of the article, please feel free to ask them in the comment area. Of course, you can also send me a private message and I will reply as soon as possible! !

It is not easy for new bloggers to create. If you feel that the content of the article is helpful to you, you might as well read it three times in a row before leaving. Your support is my motivation to update! ! !

**(Keli asks you to support the blogger three times in a row!!! Click on the comments below to like and collect to help Keli)**

Insert image description here

Guess you like

Origin blog.csdn.net/syf666250/article/details/133866270