1

我想我想要做的是这样的事情(像马可一样表达)。

    #define x->send(str)  x->send(my(x, str))

内部函数“我的”

    char *my(X x, char *d)
    {
        strcat(d, x->name);  // assuming no memory problem
    }

基本上,需要附加有关 x 的更多信息。当然,还有其他方法。但是我想保持对代码的最小更改,并且没有办法修改 X 类。谢谢!

下面列出的示例代码。

    #include <stdio.h>
    #include <string.h>

    #define x->send(y)    (x->send(my(x,y)))

    class H
    {
    public:

      char name[16];

      void send(char *str)
      {
        printf("%s", str);
      }

      H()
      {
        strcpy(name, "adam");
      }
    };

    char *my(H x, char *y)
    {
      strcat (y, "from ");
      return strcat(y, x->name);
    }

    int main()
    {
      H *h = new H;

      char str[32];
      strcpy(str, "hello ");

      h->send(str);

      return 0;
    }
4

2 回答 2

1

如果你不能修改 X,我认为下一个最好的选择是在你的源代码上做一个正则表达式替换来调用你的包装函数。即使可以定义这样的宏,也会导致无法维护的噩梦。

于 2012-08-10T17:36:22.057 回答
1

使用包装类。

class DiagnosticH : public H {
public: void send(char *str) { H::send(my(this, str)); }
};
#define H DiagnosticH // optional
于 2012-08-10T18:46:49.760 回答