Jedna reguła definicji i różne definicje klas w dwóch jednostkach tłumaczeniowych

Jest ten kod:

plik a.hpp:

class A;

plik a.cpp:

#include "a.hpp"

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

A a_zew;

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

Więc klasaA jest zdefiniowany zarówno w plikumain.cpp ia.cpp istnieją również dwa obiekty tych klas zdefiniowane w każdej jednostce tłumaczeniowej. Definicja w obu jednostkach tłumaczeniowych klasyA jest inny, ale ten kod się kompiluje. Jednak jedna reguła definicji mówi, że w programie może istnieć wiele definicji typu (ale tylko pojedyncze w każdej jednostce tłumaczeniowej) i te definicje powinny być takie same. Dlaczego więc ten kod się kompiluje, nawet jeśli definicja klasyA jest inny w obu plikach?

questionAnswers(1)

yourAnswerToTheQuestion