如果我注释掉换行符,为什么'string'会成为一个不合格的变量

Why would 'string' become an ineligible variable if I comment out Newline

本文关键字:变量 不合格 一个 string 注释 换行符 如果 为什么      更新时间:2023-10-16

在这里完成新手,我有一个关于代码中换行符的快速问题。所以我知道插入using namespace std是不好的做法,在编写我的程序时,我避免使用coutcin,而不先添加std::部分。但我想既然我没有导入命名空间库,我可以将其注释掉。但是当我这样做时,我的变量string名称变得无法识别(它下面的红线(。当我允许再次导入命名空间时,红线消失了。变量string是否仅在命名空间库中可用?

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
//using namespace std;

// read and compare names
int main()
{
std::cout << "Please enter two names n";
string first;
string second;
std:: cin >> first >> second; // read two strings
if (first == second) std::cout << "that's the same name twice! n";
if (first < second) std::cout << first << " is alphabetically before " 
<< second << 'n';
if (first > second) std::cout << first << " is alphabetically after " << 
second << 'n';
return 0;
}

如果你不包括using namespace std那么你将需要说

std::string first;
std::string second;

因为string也在standard命名空间中定义(以及cout等(。

所以是的,你是对的,string只在standard中定义.string是一个对象(不是基元类型(,正是这一点允许您进行if(first==second)比较。否则,比较字符串的"正常"方法是使用strcmp()或类似。