1

我正在尝试存储预处理器常量的值,然后“覆盖”它。

我的问题:下面的代码尝试将预处理器常量的值存储在变量“A”中,然后代码取消定义该变量,然后重新定义它,使其具有新值。问题是变量“A”具有新定义的值而不是旧值,如果这有意义的话。我可以存储预处理器常量值而不是它的引用(这似乎正在发生)?

#ifdef CUSTOM_EVENT_CALLBACK_DEFINED
  #define SUB_CUSTOM_EVENT_CALLBACK_DEFINED CUSTOM_EVENT_CALLBACK_DEFINED
  #undef CUSTOM_EVENT_CALLBACK_DEFINED
#endif
#define CUSTOM_EVENT_CALLBACK_DEFINED "def"

int main()
{
    printf(CUSTOM_EVENT_CALLBACK_DEFINED);     // prints out "def". 
    printf("\n");
    printf(SUB_CUSTOM_EVENT_CALLBACK_DEFINED); // prints out "def". I was hoping this would be "abc"
    printf("\n");

    system("PAUSE");
    return 0;
}

// Usage: where the function def is a callback function for a window in a civil engineering program that runs ontop of windows
int def(int id, int cmd, int type)
{
    #ifdef SUB_CUSTOM_EVENT_CALLBACK_DEFINED
      SUB_CUSTOM_EVENT_CALLBACK_DEFINED(id, cmd, type);
    #endif

    // perform my custom code here
}
4

1 回答 1

2

简短的回答 - 不,这是不可能的。宏不能那样工作。

但我怀疑你真的需要这样做。例如,一种解决方法是在覆盖之前将值存储在变量中:

#ifdef CUSTOM_EVENT_CALLBACK_DEFINED
  std::string SUB_CUSTOM_EVENT_CALLBACK_DEFINED = CUSTOM_EVENT_CALLBACK_DEFINED;
  #undef CUSTOM_EVENT_CALLBACK_DEFINED
#else
  std::string SUB_CUSTOM_EVENT_CALLBACK_DEFINED = "";
#endif

#define CUSTOM_EVENT_CALLBACK_DEFINED "def"

int main()
{
    printf(CUSTOM_EVENT_CALLBACK_DEFINED);     // prints out "def". 
    printf("\n");
    printf(SUB_CUSTOM_EVENT_CALLBACK_DEFINED); // prints out "def". I was hoping this would be "abc"
    printf("\n");

    system("PAUSE");
    return 0;
}

或者根本不为此目的使用宏。

于 2012-11-20T05:05:57.873 回答