为什么在c ++语言中使用命名空间std是必须的?

1 c++ using

这是一个简单的程序,我的问题是要知道为什么使用命名空间std是必须的?为什么不使用这个程序就不遵守程序?

#include <iostream>

using namespace std;

int main(){

    int a , b , c , d;

    cout << "Enter First Value" <<endl;
    cin >> a;

    cout << "Enter Second Value" <<endl;
    cin >> b;

    cout << "Enter 1 to add values" << endl  << "Enter 2 to subtract values" <<endl  <<"Enter 3 to multiply values" <<endl ;
    cin >> c;

    if (c == 1){    
        d = a + b;
        cout << "After Adding your answer is " << d << endl;
    }

    else if (c == 2){
        d = a - b;
        cout << "After Subtracting your answer is " << d << endl;
    }

    else if (c == 3){
        d = a * b;
        cout << "After Multiplication your answer is " << d << endl;
    }
    else{
        cout << "You Enter Invalid operation to perform";   
    }

    system("pause");  //buitin function to stop the comand screen.

    return 0;
} 
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 11

为什么使用命名空间std是必须的?

事实并非如此.

事实上,我会建议反对.

但是,如果您不编写using namespace std,则需要完全限定从标准库中使用的名称.这意味着std::string代替string,std::cout而不是cout等等.

如果你的书已经没有告诉你,那么你需要一本更好的书.

  • 请注意,您可以在函数内部使用`using namespace std;`,在某些情况下可能更容易接受. (7认同)

Vol*_*And 8

你不应该(但可以)使用

using namespace std;
Run Code Online (Sandbox Code Playgroud)

您可以std::在该命名空间中的每个对象之前使用,例如:

std::cout << "Enter First Value" << std::endl;
std::cin >> a;
Run Code Online (Sandbox Code Playgroud)