如何将函子和函数指针一起使用?无法将函数分配给函数指针

  • 本文关键字:函数 指针 分配 一起 c++11
  • 更新时间 :
  • 英文 :


我只是在试用c++11。我想在同一个程序中演示函子和函数指针,但我一直收到错误。如何将函子和指针一起使用?无法将函数分配给函数指针。无法将函数test1和test2分配给函数指针foo无法将Functortest*分配给void。这是我遇到的错误。我该怎么办,为什么我不能将函数分配给函数指针foo和foo1

#include<iostream>
#include<string>
using namespace std;

class Functortest{
public:
Functortest(){
//foo=void(*)();
//void(*foo1)(string);
}
void operator()(int option){
switch (option){
case 1: 
void(*foo)();
foo=test1;
break;
case 2:
void(*foo1)();
foo = test2;
}
};
void test1(){
cout << "TEST1 CALLED";
}
void test2(string msg){
cout << "TEST2 CALLED msg:  "<< msg;
}
private:
void *foo;
void *foo1;
/*void(*foo)();
void(*foo1)(string);*/
};
void main(){
Functortest funct;
funct(1);
funct(2);
}

parashift C++常见问题解答包含了一些关于如何使用成员函数指针的信息。

#include<iostream>
#include<string>
//using namespace std; // <-- better avoid `using namespace` at file scope

class Functortest {
public:
Functortest()
: foo(&Functortest::test1)   // better use the mem-initializer-list
, foo1(&Functortest::test2)  // to initialize members
{}
void operator()(int option){
switch (option){
case 1: 
(this->*foo)();
foo = &Functortest::test1;    // after the call?
break;
case 2:
(this->*foo1)("Hello World"); // need to pass an argument
//foo = &Functortest::test2;  // <-- this won't work! (A)
break;                        // better always end with a break
}
};
void test1() {
std::cout << "TEST1 CALLEDn";
}
void test2(std::string msg) {
std::cout << "TEST2 CALLED msg: " << msg << "n";
}
private:
void (Functortest::*foo)();             // declares a data member foo
void (Functortest::*foo1)(std::string); // declares a data member foo1
};
int main() {             // NOT `void main`
Functortest funct;
funct(1);
funct(2);
}

在用// <-- this won't work! (A):评论的行上

从数据成员foofoo1的声明中可以看出,这两个成员具有不同的类型:

  • foo的类型为void (Functortest::*)(),即foo是指向类Functortest的成员函数的指针,该类不接受任何参数,也不返回任何东西。它与指向类Functortest的特定成员函数test1的指针的类型相同。

  • foo1的类型为void (Functortest::*)(std::string),即foo1是指向类Functortest的成员函数的指针,该类具有std::string类型的参数,并且不返回任何。它与指向类Functortest的特定成员函数test2的指针的类型相同。

不带参数的函数不能用参数(琐碎)调用,类似地,有参数的函数也不能用无参数调用。因此,foofoo1的类型是不兼容的。出于同样的原因,不能将指向Functortest::test1的指针分配给指向成员函数[…]的指针,该函数接受类型为std::string的参数。

最新更新