C++ 中的成员与方法参数访问 [英] Members vs method arguments access in C++

查看:24
本文介绍了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.

这篇关于C++ 中的成员与方法参数访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆