gpt4 book ai didi

c++ - 将其他 header 包含到包含类定义的 header 中

转载 作者:搜寻专家 更新时间:2023-10-31 00:50:29 24 4
gpt4 key购买 nike

为什么我们需要将 header (如 stringiostream)包含到包含类定义的 header 中(类需要 I/O 或字符串按比例分配)- 作为 header 已包含在包含此类 header 的 cpp 翻译单元中。

好像内容加倍了。标题 Material 不是先粘贴到包含它的 cpp 文件中吗?

例子:

 //HEADER
#ifndef SAMPLE_H
#define SAMPLE_H

class sample
{
public:
sample();
}

sample::sample()
{
cout<<"Constructor!!!\n"; //error
}

#endif


//CPP
#include<iostream>
#include"m.h"

using namespace std;

int main()
{
m obj();
return 0;
}

抛出的错误是:

error: ‘cout’ was not declared in this scope

即使我在 cpp 文件中使用了 using namespace std。因此,要么我必须在类定义文件中包含 iostream,要么在使用 cout 之前使用 std - 但为什么呢?由于 iostream 和命名空间已经包含在主翻译单元中。

最佳答案

对于初学者来说,请注意类定义中有一个拼写错误。您忘记在类定义后放置分号

class sample
{
public:
sample();
};
^^^

在某些上下文中使用的名称在使用之前应该已经声明。

因此,如果类定义引用例如标准类 std::string,则 header <string>应该包括在内。

请注意, header 可能会被其他不知道自己需要包含 header 的用户或编译单元使用 <string>在将 header 与类定义一起使用之前。

在您的标题示例中,您必须包含标题 <iostream>或者使用限定名称 std::cout或对 std::cout 使用 using 声明或对命名空间 std 使用指令.

否则此 header 可能会导致错误,因为 header 的用户可能会忘记包含 header <iostream>在他们的程序中包含您的 header 之前。

关于c++ - 将其他 header 包含到包含类定义的 header 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com