简体   繁体   中英

C++, #ifdef question

Not coding in C++ right now but a question came up when I have a question in 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? A compile error or no error but the methodA AND those statements calling that method will not be compiled? 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. 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. 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.

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(); has to be in the body of a function.

You'll get compile errors at the lines a.methodA(); (or perhaps linker errors if the code is split across multiple translation units with inconsistent definitions of class 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方法。

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