在C ++中将字符串声明为std:string [英] Declaring strings as std:string in C++

查看:271
本文介绍了在C ++中将字符串声明为std:string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是基于GCC / G ++,通常在Ubuntu上。



下面是我完成的示例程序:

  #include< iostream> 

using namespace std;

int main()
{

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

上述代码可以正常工作。



但我有两个问题,我不太会得到...


  1. std:string 也可以正常工作。有什么区别。


  2. 如果我在类中使用 std :: string 变量,我得到一个错误错误:'std'不命名类型。此声明的示例:





  
{
private:
std:string N;


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

解决方案


将字符串声明写为std:string也很好。有什么区别。


如果格式不同,区别会更清楚:


$ b b

  std:
string c =Test;

您正在宣告一个标签,名为 std ,并使用使用命名空间std; string c>。正确地写为 std :: string ,您使用中的 string

如果我使用 std :: string

$ c>在类中声明一个私有变量,我得到一个错误错误:'std'不命名一个类型。


< blockquote>

这是因为你不能把标签放在类定义中,只能在代码块中。你必须正确写入 std :: string 。 (如果类在头中定义,则 using namespace std 是一个比源文件更糟的主意,所以我敦促你不要这样做。)

此外,如果您使用 std :: string ,那么您应该 #include< ; string> 。看起来你的代码工作原理是由于< iostream> 拉入更多的定义比它需要,但你不能移植依赖。

This is based on GCC/G++ and usually on Ubuntu.

Here's my sample program I've done:

#include <iostream>

using namespace std;

int main()
{

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

The above code works fine.

But I have two issues that I don't quite get...

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

  2. 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. Example of this declaration:

class KType
{
private:
  std:string N;

Can someone please explain these issues? Many thanks!

解决方案

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

The difference would be slight clearer if you formatted it differently:

std:
    string c = "Test";

You're declaring a label called std, and using the name string which has been dumped into the global namespace by using namespace std;. Writing it correctly as std::string, you're using the name string from the std namespace.

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.

That's because you can't put a label in a class definition, only in a code block. You'll have to write it correctly as std::string there. (If the class is defined in a header, then using namespace std is an even worse idea than in a source file, so I urge you not to do that.)

Also, if you're using std::string, then you should #include <string>. It looks like your code works by accident due to <iostream> pulling in more definitions than it need to, but you can't portably rely on that.

这篇关于在C ++中将字符串声明为std:string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆