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

Members vs method arguments access in C++(C ++中的成员与方法参数访问)
本文介绍了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 ++中的成员与方法参数访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)