我想设置一个函数指针作为类的成员,它是指向同一类中另一个函数的指针。我这么做的原因很复杂。
在本例中,我希望输出为"1“
class A {
public:
int f();
int (*x)();
}
int A::f() {
return 1;
}
int main() {
A a;
a.x = a.f;
printf("%d\n",a.x())
}
但这在编译时失败了。为什么?
发布于 2010-03-08 23:57:36
语法错误。成员指针是与普通指针不同的类型类别。成员指针必须与其类的对象一起使用:
class A {
public:
int f();
int (A::*x)(); // <- declare by saying what class it is a pointer to
};
int A::f() {
return 1;
}
int main() {
A a;
a.x = &A::f; // use the :: syntax
printf("%d\n",(a.*(a.x))()); // use together with an object of its class
}
a.x
还没有说明要在哪个对象上调用该函数。它只是说明您想要使用存储在对象a
中的指针。另一次将a
作为左操作数添加到.*
运算符将告诉编译器在哪个对象上调用函数。
发布于 2010-03-08 23:59:38
int (*x)()
不是指向成员函数的指针。指向成员函数的指针编写如下:int (A::*x)(void) = &A::f;
。
发布于 2016-05-28 22:39:34
Call member function on string command
#include <iostream>
#include <string>
class A
{
public:
void call();
private:
void printH();
void command(std::string a, std::string b, void (A::*func)());
};
void A::printH()
{
std::cout<< "H\n";
}
void A::call()
{
command("a","a", &A::printH);
}
void A::command(std::string a, std::string b, void (A::*func)())
{
if(a == b)
{
(this->*func)();
}
}
int main()
{
A a;
a.call();
return 0;
}
注意(this->*func)();
和用类名void (A::*func)()
声明函数指针的方法
https://stackoverflow.com/questions/2402579
复制相似问题