简体   繁体   中英

One definition rule and different class definitions in two translation units

There is this code:

file a.hpp:

class A;

file a.cpp:

#include "a.hpp"

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

A a_zew;

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;
}

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?

There is this code:

file a.hpp:

class A;

file a.cpp:

#include "a.hpp"

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

A a_zew;

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;
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM