关于 using namespace std

发布时间 2023-05-29 18:15:21作者: Auditorymoon

我刚接触c++,写Hello, World 是这个样子的

#include <bits/stdc++.h>
using namespace std;
int main()
{
     cout << "Hello, World" << endl;
     return 0;            
}

但是一直令我不解的是

using namespace std;

这东西这么麻烦写他干嘛?

今天我在写随机生成数据时发现了一位大佬写的(不知道网址了,还请大佬看见时与我联系)

#include <iostream>
#include <ctime>
#include <cstdlib>
 
int getRand(int min, int max);
 
int main() 
{

    
    freopen("test.txt","w",stdout);
    
    srand(time(0));
 
    for (int i=0; i<10; i++) 
    {
        int r = getRand(1, 100); // 生成数的区间在1 —— 100;
        std::cout << r << std::endl;
    }
 
   
}
    
    int getRand(int min, int max) 
    {
    return ( rand() % (max - min + 1) ) + min ;
    }

结果我定睛一看,这不就没写?

于是我上网一搜

"using namespace std;" 是 C++ 程序中常用的一个语句,它告诉编译器在当前程序中使用 "std" 命名空间中的符号。 "std" 是 C++ 标准库的缩写,里面包含了许多常用的函数和类型,如 cout、endl、string 等。使用 "using namespace std;" 可以省去在使用这些符号时前缀 "std::" 的麻烦。

得,不写更麻烦了呢,6。