Introduction to C++ 1


img

Introduction to C++ 1

1. Namespace

1.1. Namespace definition

What is namespace? It is a way to encapsulate related functions and data together to avoid name conflicts and improve the readability and maintainability of the code. We know that the writing of a large-scale project is not written by one person. It is usually completed by several to dozens of people. Each person completes a module and is finally merged. With so many people writing projects at the same time, naming conflicts will inevitably occur, such as functions with the same name or variables with the same name. So how to solve this problem? The answer is for everyone to create their own namespace.

  • To define a namespace, use the namespace keyword, followed by the name of the namespace, followed by {}, {} are members of the namespace.
#include <stdio.h>
#include <stdlib.h>

int rand = 10;
// C语言没办法解决类似这样的命名冲突问题,所以C++提出了namespace来解决
int main()
{
 		printf("%d\n", rand);
		return 0;
}
// 编译后后报错:error C2365: “rand”: 重定义;以前的定义是“函数”

1.2. Use of namespace

  • We already know how to create a namespace, so how to use the members in the namespace? as follows:

    #include <stdio.h>
    
    int y = 0;
      
    namespace xp {
          
          
        int x = 0;
    
        int Add(int a, int b) {
          
          
            return a + b;
        }
    
        typedef struct Stack {
          
          
            int *data;
            int capacity;
            int size;
        } ST;
    
    }
    
    int main() {
          
          
      	//这里编译报错,找不到ST
      	ST* st;
        //这里编译报错,找不到变量x
        printf("%d", x);
      	printf("%d", y);
        return 0;
    }
    
  • How to solve the problem that after creating a namespace and placing members in it, the member cannot be found outside? There are three solutions:

    1. Use the namespace name plus the scope qualifier:: (two colons):

    int main() {
        xp::ST *st;
        printf("%d", xp::x);
        printf("%d", y);
        return 0;
    }
    

    2. Open the namespace and release all members inside: useusing namespace 命名空间名称:

    using namespace xp;
    
    int main(){
      ST* st;
    	printf("%d", x);
      printf("%d", y);
      return 0;
    }
    

    3. Only open the space of a certain member and release this member. Other members still need to add scope qualifiers to access: (Commonly used

    using xp::ST;
    
    int main(){
      ST* st;
    	printf("%d", xp::x);
      printf("%d", y);
      return 0;
    }
    
  • Note: The namespace can be created by nesting dolls, and accessing the members inside also requires the use of nested dolls using scope qualifiers:

    #include <stdio.h>
    
    int y = 0;
    
    namespace xp {
        int x = 0;
    
        namespace zl {
            int Add(int a, int b) {
                return a + b;
            }
    
            namespace xpzl {
                typedef struct Stack {
                    int *data;
                    int capacity;
                    int size;
                } ST;
            }
        }
    
    }
    
    
    int main() {
        printf("%d", xp::x);
        xp::zl::Add(2, 3);
        xp::zl::xpzl::ST *st;
        printf("%d", y);
        return 0;
    }
    

2. Input & output

  • Let’s look at a piece of code from when we first started learning C++:

    #include<iostream>
    // std是C++标准库的命名空间名,C++将标准库的定义实现都放到这个命名空间中
    using namespace std;
    int main()
    {
    		cout<<"Hello world!"<<endl;
    		return 0;
    }
    
    • Here we see that#include is no longer<stdio.h>, but has become<iostream>. In C++, Generally, input and output no longer use scanf and printf, but cin and cout. Among them, this iostream is the **io stream**, which contains cout、cin、endl(类), stream insertion operator<< and == stream extraction operators==>>. The stream insertion operator<< is used for output, and the stream extraction operator>> is used for input. (It’s enough to know that you have such knowledge. I will go into more detail later)

    • also foundcout, cout is the standard output stream, Used with stream insertion operator<<. Similarly, cin is the standard output stream, together with the stream extraction operator>> use.

    • endl is a newline character, equivalent to "\n" in C language.

    • uses using namespace std; here, which is equivalent to opening the namespace std, of which cout、cin、endl are all in this namespace a member of. So using cout、cin、endl does not require a scope qualifier.

      #include<iostream>
      
      int main()
      {
        	//这里编译报错,找不到cout和endl
      		cout<<"Hello world!"<<endl;
      		return 0;
      }
      
  • Compared with C language, C++'s input and output is much more advanced. It can automatically identify the type of variables!

    int main() {
        int a;
        double b;
        char c;
        string d;
        // 可以自动识别变量的类型
        cin >> a;
        cin >> b >> c >> d;
        cout << a << d << endl;
        cout << b << " " << c << endl;
        return 0;
    }
    
    • string is a new data type, equivalent to C language's char [n] (a character array of length n), which will be discussed later.
    • Here is a question: How does C++ control the output precision of floating point numbers? A simple way is to use C languageprintf, because C++ is compatible with most C language syntax.

3. Default parameters

3.1. Concept of default parameters

  • The default parameter is to specify a default value for it when declaring the function, so that the parameter does not need to be specified when the function is called. The reason for using default parameters is to reduce the number of parameters when calling functions, simplify the code, and improve readability and ease of use.

    void Func(int a = 0) {
          
          
        cout << a << endl;
    }
    
    int main() {
          
          
        Func();   // 没有传参时,使用参数的默认值
        Func(10); // 传参时,使用指定的实参
        return 0;
    }
    

3.2. Default parameter classification

  • All default parameters: that is, all parameters of the function have default values.

    void Func(int a = 10, int b = 20, int c = 30) {
          
          
        cout << "a = " << a << endl;
        cout << "b = " << b << endl;
        cout << "c = " << c << endl;
    }
    
  • Semi-default parameters: Not all function parameters have default values. But there are rules:The rule is that can only be omitted from starting from the last parameter when calling, and the default value must is a constant, and default parameters cannot appear in both function declaration and definition

    • feasible:

      void Func(int a, int b = 20, int c = 30) {
          cout << "a = " << a << endl;
          cout << "b = " << b << endl;
          cout << "c = " << c << endl;
      }
      
    • Not feasible:

      //a.h
      void Func(int a = 10);
      
      // a.cpp
      void Func(int a = 20) {}
      
      // 注意:如果声明与定义位置同时出现,恰巧两个位置提供的值不同,那编译器就无法确定到底该用那个缺省值。
      

OKOK, that’s all for this issue. Next, I will share Getting Started 2, Getting Started 3…, Advanced Chapter 1, Advanced Chapter 2…. Let’s work together and make progress together!

Guess you like

Origin blog.csdn.net/qq_44121078/article/details/133779662