会员VS方法的参数用C ++访问 [英] Members vs method arguments access in C++

查看:149
本文介绍了会员VS方法的参数用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的这个或Python的

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.

如果您的绝对需要的有变量和参数调用相同的,那么你可以使用这个指针是具体的:

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.

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

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