【发布时间】:2019-07-16 01:58:24
【问题描述】:
所以我在玩编译单元时偶然发现了这一点。
我有 2 个标题,它们定义了一个同名的类。第一个编译单元包含第一个头文件并声明指向该类的外部指针,第二个编译单元包含第二个头文件并定义指针。
现在我有 T* 指向一个 U。
麦克维:
h1.h
#pragma once
struct a_struct {
int i;
a_struct(int _i) : i{ _i } {}
};
h2.h
#pragma once
struct a_struct {
float f;
a_struct(float _f) : f{ _f } {}
};
foo.h
#pragma once
struct foo {
int bar();
};
cu1.cpp
#include "foo.h"
#include "h1.h"
extern a_struct* s;
int foo::bar() {
return s->i;
}
cu2.cpp
#include "h2.h"
a_struct* s = new a_struct(1.0f);
main.cpp
#include "foo.h"
#include <iostream>
int main() {
foo f;
std::cout << f.bar() << std::endl; // <- 1065353216
system("PAUSE");
return 0;
}
为什么链接器看不到 h1.h::a_struct 不是 h2.h::a_struct ?这在标准中是否被称为未定义行为?
(我也知道用相同的名字命名 2 个类是愚蠢的......)
【问题讨论】:
标签: c++ visual-c++