这两个标题有什么区别?
我有这两个头文件,如果我不在所有字符串声明前面放置 std::
,一个会产生错误,而另一个则不会。我只是想知道两者之间有什么区别。
如果 std::
不在字符串声明前面,以下代码将产生错误:
#include <string>
#include <vector>
#pragma once
#ifndef DATABASE_H
#define DATABASE_H
struct Item
{
public:
std::string object;
int numOfColors;
std::string colors;
int sizeSmall;
int sizeLarge;
};
class database
{
private:
void fillDatabase(std::vector<Item>);
public:
void getDatabase(std::vector<Item>);
};
#endif
以下代码不会产生错误:
#include <string>
#pragma once
#ifndef GUISTRUCT_H
#define GUISTRUCT_H
struct guiValues
{
public:
string shape;
string color;
int width;
double squareProbability;
double rectangleProbability;
double circleProbability;
string firstMostLikelyObject;
double FMLOprobability;
string secondMostLikelyObject;
double SMLOprobability;
string thirdMostLikelyObject;
double TMLOprobability;
};
#endif
I have these two header files and one produces an error if I don't put std::
in front of all string declarations and the other doesn't. I was just wondering what the difference between the two was.
The following will produce an error if the std::
is not in front of the string declarations:
#include <string>
#include <vector>
#pragma once
#ifndef DATABASE_H
#define DATABASE_H
struct Item
{
public:
std::string object;
int numOfColors;
std::string colors;
int sizeSmall;
int sizeLarge;
};
class database
{
private:
void fillDatabase(std::vector<Item>);
public:
void getDatabase(std::vector<Item>);
};
#endif
The following code will not produce an error:
#include <string>
#pragma once
#ifndef GUISTRUCT_H
#define GUISTRUCT_H
struct guiValues
{
public:
string shape;
string color;
int width;
double squareProbability;
double rectangleProbability;
double circleProbability;
string firstMostLikelyObject;
double FMLOprobability;
string secondMostLikelyObject;
double SMLOprobability;
string thirdMostLikelyObject;
double TMLOprobability;
};
#endif
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第二个文件包含在其他定义的文件之后
The second file is included after some other that defines
string
在命名空间 std
中声明。因此需要使用命名空间 std 来使用字符串。可以通过两种方式完成:通过明确提及您想要从 std 命名空间包含哪种类型(在本例中为字符串),如情况 1 所示,
std::string color
或
通过启用整个 std 命名空间,
using namespace std;
从全局命名空间中的命名空间导入所有类型。(请注意,不建议在标头中执行此操作)在第二种情况下,您似乎已包含特定包含之前的整个 std 命名空间,因此即使没有明确提及 std::String 也不会给出错误
string
is declared in thenamespace std
. So one needs to use the namespace std to make use of string. it can be done in two ways:By explicitly mentioning which type(string in this case) you want to include from the std namespace as in case 1,
std::string colors
OR
By enabling the entire std namespace,
using namespace std;
which imports all types from the namespace in your global namespace.(Please note that Doing this in headers is not recommended)In the second case seems you have included the entire std namespace before the particular include and hence it is not giving an error even without exlpicit mention of
std::String