What does using namespace std; do?

后端 未结 3 510
旧时难觅i
旧时难觅i 2021-01-29 17:03

What is the matter with this C++ code?

I get an error message saying: that there should be a ; before z, which is not correct. The only part t

3条回答
  •  盖世英雄少女心
    2021-01-29 17:28

    To begin to explain what this does, it is important for you to understand what namespaces do. Namespaces are logical units of code divided up, you are able to create your own namespace or use other namespaces. The benefit of using namespaces is to have your program logically divide up your code with like functions. This is very similar to classes, but you do not need initiation of the namespaces like classes do. IN Java this would be similar to packages. To use a function within a namespace you need to use the namespace identifier followed by the function you are calling. This will call the correct function in the namespace scope you are wanting to use. An example of creating a namespace is the following:

    namespace connection 
    {
     int create_connection();
     int close_connection();
     //ect.......
    }   
    

    Then later in the code when you want to call create_connection you need to do it the following way:

    connection::create_connection();
    

    As for your answer you are able to prevent from having to type the namespace identifier in this case connection, or in your case std. You are able to introduce an entire namespace into a section of code by using a using-directive. This will allow you to call the functions that are in that namespace without needing to use the namespace followed with the scope indicator" :: ".

    The following syntax to do this is as follows:

    using namespace connection:
    

    or in your case

    using namespace std;
    

    So by doing this with std you will be granting that access to std namespace which includes C++ I/O objects cout and cin to use freely without having to use the namespace and scope operator first. Though a better practice is to limit the scope to the namespace members you want to actually use. On large programs this will be cleaner why of coding as well as avoid several problems. To introduce only specific members of a namespace, such as only introducing the std::cin and std::cout, you do the following:

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

提交回复
热议问题