C++ #define我的我->

C++ #define my me ->

本文关键字:gt #define 我的 C++      更新时间:2023-10-16

我正在浏览一个旧应用程序的源代码。在这段代码中,我看到了很多"my"的用法。

它被定义为

#define my  me ->

但我不确定这到底意味着什么。这是否意味着,如果我使用"my",它将使用"this->"?

我知道这不是一个好的做法,但我需要了解它的作用。

谢谢!

编辑:

以下是作者提供的更多信息:

/*
    Use the macros 'I' and 'thou' for objects in the formal parameter lists
    (if the explicit type cannot be used).
    Use the macros 'iam' and 'thouart'
    as the first declaration in a function definition.
    After this, the object 'me' or 'thee' has the right class (for the compiler),
    so that you can use the macros 'my' and 'thy' to refer to members.
    Example: int Person_getAge (I) { iam (Person); return my age; }
*/
#define I  Any void_me
#define thou  Any void_thee
#define iam(klas)  klas me = (klas) void_me
#define thouart(klas)  klas thee = (klas) void_thee
#define my  me ->
#define thy  thee ->
#define his  him ->

但我仍然看不到"我"的定义。

#define在这方面非常简单:当你在代码中使用my时,它将被me ->取代,所以像这个这样的代码

struct X {
    char first_name[100];
    char last_name[100];
    int age;
} *me;
me = malloc(sizeof(struct X));
strcpy(my first_name, "John");
strcpy(my last_name, "John");
my age = 23;

实际上意味着

strcpy(me->first_name, "John");
strcpy(me->last_name, "John");
me->age = 23;

尽管这个技巧看起来很可爱,但对于熟悉C语法的读者来说,它是一种严重的误导。我强烈建议不要在代码中使用它。

编译器在编译时会将"my"的实例替换为"me->"。

因此,推测其意图是取消引用一个名为"me"的指针。即,如果指向的对象具有方法Dog(),而不是

me->Dog()

你可以直接使用

my Dog()

如果要使用my,则使用me ->

这将给您一个错误,除非在使用my时以某种方式合理地定义了me

class B {
public:
    void f() {}
};

#define my me ->
int main(int argc, char** argv) {
    B* b = new B();
    b my f(); // error, expanded to: b me -> f()
    B* me = new B();
    my f(); // OK, expanded to: me -> f()
    delete b;
    delete me;
    return 0;
}

但是:

#define me
#define my me ->
int main(int argc, char** argv) {
    B* b = new B();
    b my f(); //  OK, expanded to: b -> f();
    delete b;
    return 0;
}

这是一个使my成为me ->别名的宏。

考虑到me是指向某个对象的指针,预期用途似乎是允许任何成员x使用my x。因此,在给定宏的情况下,这两个将是等效的:

me->x
my x

很可能,您在代码中的某个位置也有一个类似的宏:

#define me this

这将允许您在成员函数中使用CCD_ 13而不是CCD_。预期效果是,在具有成员x的类的任何成员函数中,这两个是等价的:

my x
this->x

并且它将明确地引用当前实例的成员x,即使存在具有相同名称的局部变量也是如此——因为this->x就是这样做的。

话虽如此,这个把戏太可怕了。它不会添加任何语言中没有的东西——它只会为已经定义良好且众所周知的语法创建一个新的语法。

此外,由于是一个宏,它将非常容易地破坏完全有效的代码。例如,一旦有人试图声明一个名为myint类型的变量,这个宏可能会导致非常混乱的错误消息,因为实际生成的代码是:

// This is what is written:
int my;
// This is what it becomes:
int me ->;
// Unless the #define for me is available, in which case you get:
int this ->

我的建议,从其他评论来看,似乎有一个强烈的共识:避免这个宏,如果可能的话,删除它,并用普通成员访问来替换它的所有使用

我能想到拥有这样一个宏的唯一原因是在其他语言的翻译层中,其中me实际上与C++中的this相同,mythis ->相同。因此,除非这是C++编译器上使用的一些轻量级语言翻译层的一部分,否则需要将其删除。