【问题标题】:Why can't I use two .h file?为什么我不能使用两个 .h 文件?
【发布时间】:2021-04-11 12:35:06
【问题描述】:

当我在#include "Anna.h" 上方执行#include "George.h" 然后using namespace Anna; 时,它给了我一个错误“预期的命名空间名称”和“未知类型Human,你的意思是Anna::Human?”,但如果我输入@987654325 @上面#include "George.h",一切都很好。

所以我想我的问题是我不能包含两个头文件。但为什么?我正在学习 udemy 课程,老师的代码运行良好。

#include <iostream>
#include "Anna.h"
#include "George.h"

using namespace std;
using namespace George;

int main()
{

    Human human1;
    human1.talk();

    return 0;
}

这是 Anna.h 代码:

#ifndef HUMAN_H
#define HUMAN_H

namespace Anna
{

class Human
{
    public:

    Human();
    void talk();
    ~Human();

};

}

#endif // HUMAN_H

这是 George.h 代码:

#ifndef HUMAN_H
#define HUMAN_H

namespace George
{

class Human
{
    public:

    Human();
    void talk();
    ~Human();

};

}

#endif // HUMAN_H

【问题讨论】:

  • 您应该显示Anna.hGeorge.h 两个标题中的内容(或其中的一小部分内容)。
  • 我的钱花在你为 Anna.h 和 George.h 使用相同的包含警卫上
  • “所以我猜我的问题是我不能包含两个头文件” - 不要猜。发布足够的minimal reproducible example,我们会指出实际问题。
  • 两个文件中的包含保护是相同的! @Bathsheba 赢了!
  • @el1oz "我不确定什么是标头保护" #ifndef HUMAN_H #define HUMAN_H ... #endif.

标签: c++ header namespaces


【解决方案1】:

在 Anna 中,将 HUMAN_H 更改为 ANNA_HUMAN_H,在 George 中将 HUMAN_H 更改为 GEORGE_HUMAN_H

我没有对此进行测试,但从 cmets 的外观(以及我自己的推理)来看,这是错误的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2023-01-07
    • 2015-06-16
    相关资源
    最近更新 更多