【问题标题】:Namespace declared in Header file is not being recognized in Source File [duplicate]源文件中无法识别头文件中声明的命名空间[重复]
【发布时间】:2017-05-02 17:21:59
【问题描述】:

我在这里做错了什么?

APP.h

#pragma once

namespace App{

    enum class AppStatus{
    Exit,
    Menu,
    Run
    };

    void frameLoop();

    AppStatus state;

}

App.cpp

#include "App.h"
#include "stdafx.h"
#include <Graphic\Graphic.h>


void App::frameLoop()
{
    while (state != AppStatus::Exit) {

        Graphic::renderingSequence();
    }
}

错误

Error   C2653   'App': is not a class or namespace name App 
Error   C2065   'state': undeclared identifier  App 
Error   C2653   'AppStatus': is not a class or namespace name   App 
Error   C2065   'Exit': undeclared identifier   App     

请注意,我的命名空间 Graphic(在 \Graphic\Graphic.h 中声明)正在被编译器识别,即使我以相同的方式声明它。

【问题讨论】:

  • #include "stdafx.h" 必须始终是第一个非注释行。上面的所有行都被编译器忽略。
  • 这必须是重复的。
  • 谢谢!将不得不更多地了解#include &lt;stdafx.h&gt;的特别之处
  • @drescherjm 我没有找到任何对我有帮助的东西,因为我没想到#include 可以有可变功能

标签: c++ visual-c++ header namespaces stdafx.h


【解决方案1】:

stdafx.h(Microsoft 预编译头文件)必须位于顶部。这适用于任何打开了预编译头选项并且 stdafx.h 是标准 pch 的 Visual C++ 项目。这些是新项目的默认设置。

Purpose of stdafx.h

在命名空间 App 中定义函数的最简单和最不容易出错的方法就是 放在那里。

APP.CPP

#include "stdafx.h" // Nothing goes above this
#include "App.h"
#include <Graphic\Graphic.h>

namespace App {
    void frameLoop()
    {
        while (state != AppStatus::Exit) {
            Graphic::renderingSequence();
        }
    }
}

【讨论】:

  • 我同意 Jive 的观点,您应该将函数放在命名空间中,而不是使用 App::frameLoop()。这可能会让人们感到困惑,他们可能会认为 App 是一个类。
  • 更重要的是,cpp 文件中的代码会自动解析与 .h 文件相同的名称。例如。 AppStatus::Exit.
猜你喜欢
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多