是否每个c ++成员函数都隐式地将"this"作为输入? [英] Does every c++ member function take `this` as an input implicitly?

查看:110
本文介绍了是否每个c ++成员函数都隐式地将"this"作为输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在c ++中为类创建成员函数时,它具有一个隐式的额外参数,该参数是指向调用对象的指针-称为this.

When we create a member function for a class in c++, it has an implicit extra argument that is a pointer to the calling object -- referred as this.

对于任何函数,即使它不使用this指针,也是如此.例如,给定课程

Is this true for any function, even if it does not use this pointer. For example, given the class

class foo
{
private:
    int bar;
public:
    int get_one()
    {
      return 1;  // Not using `this`
    }
    int get_bar()
    {
        return this->bar;  // Using `this`
    }
}

两个函数(get_oneget_bar)是否都将this作为隐式参数,即使其中只有一个实际上使用了它?
这样做似乎有点浪费.

Would both the functions (get_one and get_bar) take this as an implicit parameter, even though only one of them actually uses it?
It seems like a bit of a waste to do so.

注意:我知道正确的做法是将get_one()设为静态,答案可能取决于实现,但我很好奇. /sub>

Note: I understand the correct thing to do would be to make get_one() static, and that the answer may be dependent on the implementation, but I'm just curious.

推荐答案

即使只有一个get_bar使用它,两个函数(get_one和get_bar)也都将其作为隐式参数吗?

Would both of the functions (get_one and get_bar) take this as an implicit parameter even though only onle get_bar uses it?

是的(除非编译器对其进行了优化,但这仍然并不意味着您可以在没有有效对象的情况下调用该函数).

Yes (unless the compiler optimizes it away, which still doesn't mean you can call the function without a valid object).

这样做似乎有点浪费

It seems like a bit of a waste to do so

然后,如果不使用任何成员数据,为什么它是成员?有时,正确的方法是使它成为同一名称空间中的自由函数.

Then why is it a member if it doesn't use any member data? Sometimes, the correct approach is making it a free function in the same namespace.

这篇关于是否每个c ++成员函数都隐式地将"this"作为输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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