C ++中的成员与方法参数访问

2022-01-21 00:00:00 class arguments methods instance c++

我可以有一个方法,它接受与控股类成员同名的参数吗?我试着用这个:

Can I have a method which takes arguments that are denoted with the same names as the members of the holding class? I tried to use this:

    class Foo {
        public:
            int x, y;
            void set_values(int x, int y)
            {
                x = x;
                y = y;
            };
    };

...但它似乎不起作用.

... but it doesn't seem to work.

有什么方法可以访问我正在使用的命名空间的实例,类似于 JavaScript 的 this 或 Python 的 self?

Is there any way of accessing the the instance the namespace of which I'm working in, similar to JavaScript's this or Python's self?

推荐答案

通过使用成员变量的命名约定来避免这种混淆通常是一个好主意.例如,camelCaseWithUnderScore_ 很常见.这样你会得到 x_ = x;,大声读出来还是有点好笑,但在屏幕上却相当明确.

It's generally a good idea to avoid this kind of confusion by using a naming convention for member variables. For example, camelCaseWithUnderScore_ is quite common. That way you would end up with x_ = x;, which is still a bit funny to read out loud, but is fairly unambiguous on the screen.

如果您绝对需要将变量和参数调用相同,那么您可以使用 this 指针来具体说明:

If you absolutely need to have the variables and arguments called the same, then you can use the this pointer to be specific:

class Foo {
    public:
        int x, y;
        void set_values(int x, int y)
        {
            this->x = x;
            this->y = y;
        }
};

顺便说一下,注意类定义后面的分号――这是成功编译所必需的.

By the way, note the trailing semi-colon on the class definition -- that is needed to compile successfully.

相关文章