其他分享
首页 > 其他分享> > 在C中将字符串声明为std:string

在C中将字符串声明为std:string

作者:互联网

这基于GCC / G,通常在Ubuntu上.

这是我做过的示例程序:

#include <iostream>

using namespace std;

int main()
{

std::string c = "Test";
cout << c;
return 0;
}

上面的代码工作正常.

但我有两个问题,我不太明白……

>将字符串声明写为std:string也可以正常工作.有什么不同.
>如果我在一个类中使用这个std :: string来声明一个私有变量,我会收到一个错误错误:’std’没有命名一个类型.此声明的示例:

06001

有人可以解释一下这些问题吗?
非常感谢!

解决方法:

Writing the string declaration as std:string also works fine. What’s the difference.

如果您对其进行不同的格式化,差异会更加清晰:

std:
    string c = "Test";

您正在声明一个名为std的标签,并使用名称字符串,该字符串已使用namespace std;转储到全局名称空间中.正确地将其写为std :: string,您将使用std命名空间中的名称字符串.

If I use this std::string within a class to declare a private variable, I get an error error: ‘std’ does not name a type.

那是因为你不能只在代码块中将标签放在类定义中.你必须在那里正确编写std :: string. (如果在头文件中定义了类,那么使用命名空间std比在源文件中更糟糕,所以我强烈建议你不要这样做.)

另外,如果你正在使用std :: string,那么你应该#include< string>.由于< iostream>而您的代码看起来像是偶然的.引入更多的定义而不是它需要,但你不能依赖它.

标签:c,string,private-members
来源: https://codeday.me/bug/20191008/1874716.html