如何在多个 class 中定义相同的命名结构?

How do I define the same named structure in more than one class?

我从多个工程师那里得到了多个 类,我正在使用它们,它们在 类 中具有相同的命名结构。由此我得到错误“'struct' type redefinition”。我该如何解决这个问题?

示例:

// Eng1Class.h
#pragma once

struct Eng1And2SameName
{
    unsigned int bottle;
};

class Eng1Class
{
public:
    Eng1Class();
    ~Eng1Class();
};

.

// Eng2Class.h
#pragma once

struct Eng1And2SameName
{
    float x, y;
};

class Eng2Class
{
public:
    Eng2Class();
    ~Eng2Class();
};

.

// Main Program
#include "stdafx.h"
#include "Eng1Class.h"
#include "Eng2Class.h"

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

错误:错误 C2011:'Eng1And2SameName':'struct' 类型重新定义

根据这个 Compile error "'struct' type redefinition" although it's the first definition for it #pragma once 应该可以解决问题,但我仍然看到错误。您可以提供任何见解吗?

否,#pragma once 防止 header 文件被多次包含 - 每个文件被包含一次 -> 重新定义。

they have the same named structures in the classes

*header 个文件

类(嵌套)中没有定义,但它们可以是:

class Eng1Class
{
public:
    struct Eng1And2SameName
    {
        unsigned int bottle;
    };

    Eng1Class();
    ~Eng1Class();
};

或者您可以将那些 header 的内容包含在两个不同名称的 namespace 中。

定义命名空间会有所帮助

例如,正如您所说的在同一名称范围内具有相同结构定义的错误。 报错

你可以通过定义namesapce来实现

#include<iostream>
using namespace std;

namespace Eng1 {
    struct Eng1And2SameName
    {
        unsigned int bottle;

    };
}

namespace Eng2
{

    struct Eng1And2SameName
    {
        float x, y;
    };
}

int main()
{
    Eng1::Eng1And2SameName a;
    Eng2::Eng1And2SameName b;

    return 0;
}

通常从事同一产品的工程师会以某种方式进行协调,至少他们会使用共同的源代码存储库和共同的构建。因此,冲突应该更早出现。

"uncoordinated"工程师在不同产品上工作时可能会发生这种情况,如果是这样,每个产品都可以有自己的命名空间。因此,您可以组合产品而不会发生冲突:

// in a header:
namespace Eng1Class {

    struct Eng1And2SameName
    {
        unsigned int bottle;
    };

    class EngClass
    {
    public:
        EngClass();
        ~EngClass();
    };

}

// in the cpp-file
Eng1Class::EngClass::EngClass() {
    cout << "hello, Class 1";
}

// in another (or even the same) header
namespace Eng2Class {

    struct Eng1And2SameName
    {
        float x, y;
    };

    class EngClass
    {
    public:
        EngClass();
        ~EngClass();
    };
}

// in another (or even the same) cpp-file
Eng2Class::EngClass::EngClass() {
    cout << "hello, Class 2";
}