【C++】Beginning with C++

Hits: 0

First acquaintance with C++

After learning C language, I started to know C++. C++ is developed on the basis of C language, so everything in C language can run on C++. At the same time, C++ has also carried out many optimizations and realized many functions that C language cannot achieve. Let us slowly understand C++ as a programming language.

1. C++ keywords

The first is the keywords of C++. There are a total of 63 keywords in C++, including 32 keywords in the C language. For the keywords of C++, we will not introduce them one by one, but will come to know them gradually in the following study.

2. Namespace

In C/C++, variables, functions and classes to be learned later exist in large numbers, and the names of these variables, functions and classes will all exist in the global scope, which may cause many conflicts. The purpose of using namespaces is to localize the names of identifiers to avoid naming conflicts or name pollution, and the namespace keyword appears to address this problem.

1. 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 {}, where {} is the member of the namespace.
First, a common namespace, where variables, functions and types can be defined

namespace  nd //with nd as the namespace
{
    int a = 10 ; //variable 
    int b = 20 ;
     int  Swap ( int * px, int * py ) // function
    {
        int tmp = *px;
        *px = *py;
        *py = tmp;
    }
    struct gh //struct type
    {
        int age;
        char name[20];
        int weight;
    };
}

Second, namespaces can be nested, which means that one namespace can contain another namespace.

namespace ep
{
    int a;
    float b;
    char c;

    //Namespaces can be nested using 
    namespace zm
    {
        int arr[10];
        struct Node
        {
            int* data;
            struct Node* next;
        };
    }
}

Furthermore, multiple namespaces with the same name are allowed to exist in a project, and the compiler will merge all namespaces with the same name at the end.

namespace ep
{
    int a;
    float b;
    char c;

    //Namespaces can be nested using 
    namespace zm
    {
        int arr[10];
        struct Node
        {
            int* data;
            struct Node* next;
        };
    }
}

It should be noted that a namespace defines a new scope, and everything in the namespace is limited to this namespace.

namespace nd //with nd as the namespace
{
    int a = 10 ; //variable 
    int b = 20 ;
}

int  main ()
 {
     printf ( "%d\n" , a); //This statement compiles incorrectly and cannot recognize a 
    return  0 ;
}

2. The use of namespaces

After knowing the namespace, how to use the members of the namespace?
1. Use namespace names and scope qualifiers::

int main()
{
    printf("%d\n", nd::a);
    printf("%d\n", ep::zm::arr[0]);
    return 0;
}

  1. Use using to import the name of the namespace

using namespace nd;

int main()
{
    int m = 1;
    int n = 2;
    Swap(&m, &n);
    printf("m:%d n:%d\n", m, n);
    printf("%d\n", a);
    return 0;
}

One thing to note about this method of use is that the original function of the namespace is to avoid naming conflicts or name pollution, and if the namespace is directly expanded, the members of the namespace will be directly exposed, which may cause Cause name collision and name pollution, therefore, instead of directly introducing the name of the namespace, you can import the members commonly used in the namespace.
3. Use using to import members from the namespace

using nd::Add;

int main()
{
    int a = 10;
    int b = 20;
    int c = Add(a, b);
    printf("%d\n", c);
    return 0;
}

3. Input and output of C++

When I first knew the C language, I started from hello world, so what about the hello world of C++?

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
    cout << "hello world" << endl;
    return 0;
}

What needs to be explained here is:
First, when using coutstandard output (ie console) and cinstandard input (ie keyboard), you need to include <iostream>header files and stdstandard namespaces.
It should be noted that in the early days of C++, there was no concept of namespace, so all the functions of the standard library were implemented in the global scope and declared in the header file suffixed with .h. When using it, you only need to include the corresponding header file. With the gradual development of C++, the functions of the original standard library are all under the namespace std. At the same time, in order to distinguish it from the header file of the C language, and to use the namespace correctly, it is stipulated that The header files for C++ do not have .h. The format is also supported in the old compiler (vc 6.0), <iostream.h>and is not supported by subsequent compilers, so it is <iostream>+stdthe recommended way.
Secondly, the input and output in C++ do not need data format control, such as integer–“%d”, floating-point-“%f”.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
    int n = 0;
    cin >> n;
    double* a = (double*)malloc(sizeof(double) * n);
    if (a == NULL)
    {
        printf("malloc fail");
        exit(-1);
    }
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    for (int i = 0; i < n; i++)
    {
        cout << a[i] << " ";
    }
    cout << endl;
    free(a);
    a = NULL;
}

There is no need to control the data format, which is a convenient point. But there may also be troublesome situations. For example, when you want to output the information of a structure, the output of C++ is a bit verbose:

namespace ns
{
    struct Stu
    {
        char name[20];
        int age;
        char id[10];
    };
}

using namespace ns;

int  main ()
 {
     struct  Stu  s1 = {  "Li Hua" , 18 , "20200225" };
     cout << "Name:" << s1.name << " " << "Age:" << s1.age < < " " << "Student ID:" << s1.id << endl ;
     printf ( "Name: %s Age: %d Student ID: %s\n" , s1.name, s1.age, s1.id );
     return  0 ;
}

Therefore, in the actual use process, there is no need to worry about the input and output methods, just use it as it is convenient.

4. Default parameters

1. The concept of default parameters

A default parameter is when a function is declared or defined to specify a default value for a function’s parameters. When calling the function, the default value is used if no arguments are specified, otherwise the specified arguments are used.

int Add(int a, int b = 10)
{
    return a + b;
}

int  main ()
 {
     cout << Add( 10 , 20 ) << endl ; //When passing parameters, use the specified actual parameters 
    cout << Add( 10 ) << endl ; //When no parameters are passed, use the default parameter value 
    return  0 ;
}

2. Classification of default parameters

full default parameters

All default parameters means that all parameters of the function are set with default parameters.

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

int main()
{
    Test1();
    Test1( 1 );
    Test1( 1 , 2 );
    Test1(1, 2, 3);
    return 0;
}

It should be noted that when passing parameters, you can only pass them in order from left to right, and Test(,10,);statements like this cannot appear, and the compiler cannot recognize them.

semi-default parameter

Semi-default parameters are some parameters of a function that have default values ​​set.

void Test2(int a, int b = 20, int c = 30)
{
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
}

int main()
{
    Test2( 1 );
    Test2( 1 , 2 );
    Test2(1, 2, 3);
    return 0;
}

Note: (1) The default value in the semi-default parameter must be set from right to left, and Test(int a = 10, int b; int c);statements like this cannot appear, because this setting will cause ambiguity and the compiler will not recognize it.
(2) Default parameters cannot appear in the declaration and definition of a function at the same time. This is stipulated. If the default values ​​of the declared and defined parameters are not the same, the compiler will not recognize them. In order to prevent this from happening, the default parameters cannot be Appears in both function declarations and definitions.

//fun.h 
int  Add ( int a = 10 , int b = 20 ) ;
 //fun.c 
int  Add ( int a= 10 , int b = 20 ) ; //error, default parameters cannot both appear in declarations and in the definition

(3) The default value must be a constant or a global variable.
(4) The default parameters are not supported by the C language.

5. Function overloading

1. The concept of function overloading

Function overloading: It is a special case of functions. C++ allows to declare several functions of the same name with similar functions in the same scope. The formal parameter lists (the number or type or order of parameters) of these functions with the same name must be different. It is often used to deal with Implementing functionality similar to the problem of different data types.

//The function name is the same, the parameter type is different 
void  Swap ( int * px, int * py)
 {
     int tmp = *px;
    *px = *py;
    *py = tmp;
}

void Swap(double* px, double* py)
{
    double tmp = *px;
    *px = *py;
    *py = tmp;
}

int main()
{
    int a = 1;
    int b = 2;
    double c = 3.3;
    double d = 4.4;
    Swap(&a, &b);
    Swap(&c, &d);
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "c = " << c << endl;
    cout << "d = " << d << endl;
    return 0;
}

It should be noted that a function of the same name with the same parameter type and different return value does not belong to function overloading, and this situation cannot be compiled.

2. Name Mangling

First, let’s look at a question: C++ can support function overloading, so can C language support function overloading?
The answer is no, what is the reason, let’s take a look.
First of all, in C/C++, program operation needs to go through the following stages: preprocessing, compilation, assembly, and linking.
In fact, our projects are composed of multiple source files and multiple header files. According to the stages of C/C++ compilation and linking, when test.c calls the Add function defined in fc, this before the link is compiled after compilation. At this stage, there is no address of the Add function in the target file test.o, because Add is defined in fc, so the address of Add is in fo, so what should we do at this time?
At this time, it is necessary to make the link work. The linker sees that test.o calls the Add function, but does not have the address of Add, it will go to the symbol table of fo to find the address of Add, and then link it together.

Because each compiler has its own function name modification rules, when linking, the linker will look for function addresses according to different function names.
Because the decoration rules of VS are too complicated, here we take the gcc compiler under Linux as an example.
To sum up, since functions with the same name cannot be distinguished, C language cannot support function overloading, while C++ distinguishes them through the modification rules of functions. As long as the parameters are different, the modified names are different, so function overloading is supported. In addition, we can also understand why function overloading requires different parameters but not the return value.

You may also like...

Leave a Reply

Your email address will not be published.