基于ifdef的继承在C ++中的问题 [英] Problems with ifdef based inheritance in C++
问题描述
我在看一些类的代码,我遇到了这样的代码:
I was looking at the code of some class I was using, and I came across code like this:
#ifdef SOME_OBSCURE_CONDITION
class A {
#elif
class A : public B {
#endif
这样的代码可能有问题吗?
Can there be any problems with such code?
具体来说,假设x.cpp文件包含y.h和z.h。
z.h和y.h都包括a.h(定义类A),但是另外y.h定义了SOME_OBSCURE_CONDITION。在这种情况下,两个冲突的定义A不会出现在x.cpp中?
Specifically, suppose file x.cpp includes y.h and z.h. z.h and y.h both include a.h (which defines class A), but additionally y.h defines SOME_OBSCURE_CONDITION. In this case, will two conflicting definitions of A not be present in x.cpp?
推荐答案
>同时会违反ODR(一种定义规则),并可能导致
yes, the two variations simultaneously would violate the ODR (One Definition Rule) and may lead to anything ranging from
- 编译错误
- 链接错误
- 未定义的行为(包括但不限于崩溃)
只要您可以确保SOME_OBSCURE_CONDITION定义在全局上是相同的(也是跨部分构建/重新链接),则不会有问题。
As long as you can make sure that the SOME_OBSCURE_CONDITION define is globally identical (also across partial builds/relinks...) there will not be an issue.
这篇关于基于ifdef的继承在C ++中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!