一个定义规则和两个翻译单元中的不同类定义 [英] One definition rule and different class definitions in two translation units

查看:214
本文介绍了一个定义规则和两个翻译单元中的不同类定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有以下代码:

文件a.hpp:

class A;

档案a.cpp:

#include "a.hpp"

struct A {
   int x = 777;
   int y;
};

A a_zew;

文件main.cpp:

file main.cpp:

#include "a.hpp"
#include <iostream>

class A { // definition of class A is different than above
public:
   int x;
};

int main() {
   A a; // definition of class A in main.cpp
   extern A a_zew; // definition of class A in a.cpp
   std::cout << a_zew.x << std::endl; // 777
   std::cout << a.x << std::endl; // junk
   return 0;
}

所以类 A 在文件 main.cpp a.cpp 中定义,并且在每个翻译单元中还定义了这些类的两个对象。类 A 的翻译单位中的定义不同,但此代码编译。然而,一个定义规则说,在程序中可以有许多类型的定义(但每个翻译单元中只有一个),这些定义应该是相同的。那么为什么这个代码编译,即使 A 的定义在这两个文件中不同吗?

So class A is defined both in file main.cpp and a.cpp and there are also two objects of these classes defined in each translation unit. Definition in both translation units of class A is different but this code compiles. However one definition rule says that there can be many definitions of the type in the program (but only single in each translation unit) and these definitions should be the same. So why does this code compile even if definition of class A is different in both files?

推荐答案

您的程序具有未定义的行为。 C ++ 11标准的Paragaph 3.2 / 6规定:

Your program has undefined behavior. Paragaph 3.2/6 of the C++11 Standard specifies:


类类型可以有多个定义(第9条) ,[...],条件是每个定义
出现在不同的翻译单元中,并且提供的定义满足以下要求。给定
这样一个实体名为 D 在多个翻译单元中定义,然后[...]

There can be more than one definition of a class type (Clause 9), [...] in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then [...]

下面是你的程序确实违反的要求列表。但是,在列表的末尾,这里提到:

And what follows is a list of requirements that your program is indeed violating. However, at the end of the list, this is mentioned:


[...]如果 D 满足所有这些要求,
那么程序将表现得好像有一个单独的定义 D 如果 D 的定义不满足
这些要求,那么行为未定义

[...] If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.

这篇关于一个定义规则和两个翻译单元中的不同类定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆