gpt4 book ai didi

c++ - 两个本地结构,每个都在单独的 cpp 文件中 - 未定义的行为?

转载 作者:行者123 更新时间:2023-11-30 02:46:50 24 4
gpt4 key购买 nike

如果我有两个具有相同名称的struct,但它们中的每一个都写入了它自己的.cpp 文件,这真的应该是未定义的行为吗?

///////////////////////////////
// test1.h
class Foo
{
public :
void bar();
};

///////////////////////////////
// test2.h
class Foo2
{
public:
void bar();
};

///////////////////////////////
// test1.cpp
#include "test1.h"

struct Test
{
Test() :a(0){}
int a;
};

void Foo::bar()
{
Test t;
}

///////////////////////////////
// test2.cpp
#include "test2.h"

struct Test
{
Test() :a(0), b(0){}
int a, b;
};

void Foo2::bar()
{
Test t;
}

///////////////////////////////
// main.cpp
#include "test1.h"
#include "test2.h"

int main()
{
Foo2 f;
f.bar();
}

我已将它作为错误 here 报告给 Microsoft,但他们回应说,这是未定义的。是不是真的?我觉得很奇怪。

最佳答案

这确实给出了未定义的行为。 One Definition Rule 的一部分指出,如果您在多个翻译单元中定义具有外部链接的同一个类,则定义必须相同。 (规则的确切措辞相当冗长,所以我不会引用它;如果你想要血淋淋的细节,请参阅 C++11 3.2/5)。通过在两个翻译单元中以不同方式定义 Test,您违反了这条规则。

避免像这样的名称冲突的最简单方法是将本应属于本地文件的定义放在未命名的命名空间中:

namespace {
struct Test {
// whatever
};
}

关于c++ - 两个本地结构,每个都在单独的 cpp 文件中 - 未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23148504/

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