【问题标题】:How can I use types declared in a namespace inside a header file in C++? [closed]如何使用在 C++ 头文件中的命名空间中声明的类型? [关闭]
【发布时间】:2018-09-07 17:00:34
【问题描述】:

我正在使用 C++ 在 Visual Studio 2017 中制作 DirectX11 应用程序,我需要在“GeometryGenerator.h”头文件中声明一个数据结构。

问题是,当我尝试在头文件中使用类型:XMFLOAT3 时,当我尝试运行项目时,Visual Studio 出现错误并给我以下消息:

“C4430: missing type specifier - int assumed”

在我声明 XMFLOAT3 类型变量的行中

这是我的代码:

#pragma once
#include "..\Common\DeviceResources.h"
#include "ShaderStructures.h"
#include "..\Common\StepTimer.h"

namespace DirectX11Engine
{

    class GeometryGenerator {
    public: 
        struct Vertex
        {
            Vertex() {}
            Vertex(const XMFLOAT3& p, const XMFLOAT3& n, const XMFLOAT3& t, const XMFLOAT2& uv)
                : Position(p), Normal(n), TangentU(t), TexC(uv) {}
            Vertex(
                float px, float py, float pz,
                float nx, float ny, float nz,
                float tx, float ty, float tz,
                float u, float v)
                : Position(px, py, pz), Normal(nx, ny, nz),
                TangentU(tx, ty, tz), TexC(u, v) {}

            XMFLOAT3 Position;
            XMFLOAT3 Normal;
            XMFLOAT3 TangentU;
            XMFLOAT2 TexC;
        };
        void PruebaDeTipos();

    };

}

如果我添加这个:

using namespace DirectX;

我摆脱了这个问题。我的问题是头文件中的using namespaces X 在 C++ 中是否是一种糟糕且危险的做法?还有我怎样才能在 .cpp 文件中使用在它们自己的命名空间中声明的类型?

【问题讨论】:

  • 使用DirectX::XMFLOAT3 而不是XMFLOAT3
  • 在头文件中使用名称空间 foo 是不好的,特别是如果您有多个名称空间,因为这会破坏名称空间的用途。 DirectX::XMFLOAT3 是正确的方式
  • 最好总是从输出选项卡(是的输出选项卡不是错误列表)复制确切的错误消息(而不是解释)。
  • "如何使用在 .cpp 文件中的命名空间中声明的类型?" - 您只需使用他们的全名。例如DirectX::XMFLOAT3

标签: c++ header namespaces directx-11


【解决方案1】:

如何使用在 .cpp 文件中的命名空间中声明的类型?

你使用scope resolution operator,在你的情况下是这样的:

Vertex(const DirectX::XMFLOAT3& p, const DirectX::XMFLOAT3& n, const DirectX::XMFLOAT3& t, const DirectX::XMFLOAT2& uv)

...

DirectX::XMFLOAT3 Position;
DirectX::XMFLOAT3 Normal;
DirectX::XMFLOAT3 TangentU;
DirectX::XMFLOAT2 TexC;

每次您引用该命名空间中的名称时,依此类推。

第二个选项,如果您真的希望避免在头文件中为每次使用键入命名空间,请使用以下using 语法:

using XMFLOAT3 = DirectX::XMFLOAT3;

通过像这样别名,您可以使用放在= 之前的任何名称,而不是整个DirectX::XMFLOAT3。但是请注意,如果您在相对全局的上下文(例如文件或封装命名空间)中这样做,那么任何熟悉命名空间的人,例如DirectX,在检查您的代码时都必须记住您的别名,而不是到指定全名的非常容易识别和明确的第一个选项。

但是在头文件中添加命名空间是一种不好且危险的做法 在 C++ 中?

确实,请在此处查看综合说明:Why is “using namespace std” considered bad practice?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 2016-06-11
    • 1970-01-01
    • 2011-06-14
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多