简体   繁体   English

C ++,#ifdef问题

[英]C++, #ifdef question

Not coding in C++ right now but a question came up when I have a question in C#. 现在不使用C ++进行编码,但是当我在C#中遇到问题时就会出现一个问题。 Hope experts here can easily give a anwser. 希望这里的专家可以轻松给出答案。

Class A{
  #ifdef AFlag
  public void methodA(){...}
  #endif
}

Class B{
...
  A a;
  a.methodA();
...
}

Class C {
...
  A a;
  a.methodA();
...
}

If the AFlag is NOT defined anywhere, what will happen? 如果未在任何地方定义AFlag,将会发生什么? A compile error or no error but the methodA AND those statements calling that method will not be compiled? 编译错误或没有错误,但是methodA和那些调用该方法的语句将不会编译? thanks 谢谢

将会出现编译错误。

Preprocessing happens before compilation. 预处理编译之前进行 By the time your code goes to the compiler, the definition of method A in class A will be removed. 等到您的代码进入编译器时,将删除类A中方法A的定义。 Effectively its as if as you never wrote it. 实际上,就像您从未写过一样。 So this will result in compilation error. 因此,这将导致编译错误。

一类将不具有methodA所以编译类B或C将失败。

You will have a complier error, as the function methodA is not declared anywhere. 您将遇到编译器错误,因为未在任何地方声明methodA函数。 You could use this syntax instead: 您可以改用以下语法:

Class A{ 

  public void methodA()
  {
#ifdef AFlag 
    ...
#endif 
  } 

} 

Which will allow methodA to be declared / defined, but it will be optimized away if you turn optimizations on. 这将允许声明/定义methodA ,但是如果您打开优化功能,它将被优化。

Hard to say for certain, since code in the "..." could affect the answer, or mean that I've misunderstood the question. 很难确定,因为“ ...”中的代码可能会影响答案,或者意味着我误解了这个问题。 The statement a.methodA(); 语句a.methodA(); has to be in the body of a function. 必须在函数的主体中。

You'll get compile errors at the lines a.methodA(); a.methodA();行中会出现编译错误a.methodA(); (or perhaps linker errors if the code is split across multiple translation units with inconsistent definitions of class A). (如果代码在A类定义不一致的情况下跨多个翻译单元使用,则可能发生链接器错误)。 Calling a function means it has to be there. 调用函数意味着它必须存在。 The call is not "ignored" if the function doesn't exist. 如果该函数不存在,则不会“忽略”该调用。

如果AFlag ,则类A将没有成员函数methodA() ,因此在类BC对其的调用将是错误的。

您将看到编译错误,因为未在类A上定义methodA方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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