问题描述
c ++标准(ISO c ++ 11)在第9.3.1节中提到
The c++ standard (ISO c++11) mentions in Section 9.3.1 that
尝试使用g ++(版本4.8.2)编译此代码
An attempt to compile this code with g++ (version 4.8.2)
class foo{
public:
void bar(){
cout<<"hey there"<<endl;
}
};
int main(){
foo obj;
foo::bar(&obj);
}
给出了编译时错误,因为它与函数的签名不匹配。考虑到标准关于调用成员函数的规定,我认为这是可以预期的。
由于该方法在编译的某个阶段最终会采用类似于 bar(foo *)的形式,因此该标准为何要求使用成员访问语法来调用成员函数?
gives a compile time error because it couldn't match the function's signature. I guess that is expected given what the standard states about calling member functions.Since the method will eventually take a form similar to bar(foo*) during some stage of compilation, why does the standard asks for member access syntax to call the member function?
推荐答案
让我们为该类添加 static 成员,
Lets add a static member to the class as:
class foo{
public:
void bar() { cout<<"hey there"<<endl; }
static void bar(foo*) { cout<<"STATIC MEMBER"<<endl; }
};
现在,如果你这样写:
foo::bar(&obj); //static or non-static?
应该调用哪个函数?在这种情况下,您怎么称呼他们两个?语法是什么?如果您允许一个函数使用这种语法,则您必须放弃其他函数(即语法)。标准决定对 static
成员函数使用 foo :: bar(& obj)语法,而对 non-static放弃它成员函数。
Which function should be called? In such situation, how would you call both of them? What would be the syntax? If you allow one function to have this syntax, you've to abandon it (i.e syntax) for other function. The Standard decided to have foo::bar(&obj) syntax for static
member function, while abandoning it for non-static member function.
无论如何,如果要传递& obj
作为非静态成员函数的参数,则可以使用 std :: function
促进的类型擦除:
Anyway, if you want to pass &obj
as argument to the non-static member function, then you can use type-erasure facilitated by std::function
as:
void (foo::*pbar)() = &foo::bar; //non-static member function #1
std::function<void(foo*)> bar(pbar);
bar(&obj); //same as obj.bar();
同样,您可以将静态成员函数调用为:
Likewise, you could call static member function as:
void (*pbar)(foo*) = &foo::bar; //static member function #2
std::function<void(foo*)> bar(pbar);
bar(&obj); //same as foo::bar(&obj);
请注意,在#1
和#2
,对象 pbar
的类型使编译器选择正确的成员函数—在第一种情况下,它使用指向 non-static 成员函数的指针,在后一种情况下,它使用指向 static 成员函数的指针。
Note that at lines #1
and #2
, the types of the object pbar
makes the compiler to choose the correct member function — in the first case, it takes the pointer to the non-static member-function while in the latter case, it takes the pointer to the static member function.
希望有帮助。
这篇关于为什么不能将this指针显式传递给成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!