我是C ++的初学者,我正在Stroustrup的Programming Principles And Practice Using C++
做一个练习。
这个练习要我试验合法和非法的名字。
void illegal_names()
{
// the compiler complains about these which made sense:
// int double =0;
// int if =0;
// int void = 0;
// int int = 0;
// int while =0;
// string int = "hello";
//
// however, this is legal and it runs without a problem:
double string = 0.0;
cout << string<< endl;
}
我的问题是,是什么让string
与其他任何类型都不同?还有其他类型的特殊内容,例如string
吗?
答案 0 :(得分:5)
所有其他名称都是C ++语言中的保留字。但“字符串”不是。尽管string
是一种常用的数据类型,但它是由更基本的类型构建的,并在一个本身用C ++编写的库中定义。
答案 1 :(得分:0)
std::string
是定义的数据类型(类),而不是关键字。它不被禁止将其用作变量名称。这不是一个保留的词。考虑一个C ++程序,它也有效:
#include <iostream>
class xxx {
int x;
public:
xxx(int x_) : x(x_) {}
int getx() { return x;}
};
int main()
{
xxx c(4);
std::cout << c.getx() << "\n";
int xxx = 4; // this works
std::cout << xxx << "\n";
return 0;
}
与string
相同的情况。 xxx是用户定义的数据类型,您可以看到它不是保留的。
下图显示了c ++中保留关键字的列表。
答案 2 :(得分:0)
string
不是关键字,因此可以用作标识符。代码段中的所有其他statemenets都是错误的,因为使用了关键字作为标识符。
对于标准类std::string
,您甚至可以在块范围内编写
std::string string;
在这种情况下,块范围中声明的标识符string
将隐藏类型std::string
例如
#include <iostream>
#include <string>
int main()
{
std::string string = "Hello, string";
std::cout << string << std::endl;
return 0;
}