问题描述
当我们在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_one
和get_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.
推荐答案
是的(除非编译器对其进行了优化,但这仍然并不意味着您可以在没有有效对象的情况下调用该函数).
Yes (unless the compiler optimizes it away, which still doesn't mean you can call the function without a valid object).
然后,如果不使用任何成员数据,为什么它是成员?有时,正确的方法是使它成为同一名称空间中的自由函数.
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"作为输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!