[英]C++ function method via function pointer
I'm trying to understand how function pointer works can't clarified why I get the following err. 我试图了解函数指针的工作原理,无法弄清为什么我得到以下错误。
#include <iostream>
using namespace std;
enum COLOR {RED,BLACK,WHITE};
class Car
{public:
Car (COLOR c): color(c) { cout<<"Car's constructor..."<<endl; CarsNum++;}
~Car () {cout<<"Car's destructor..."<<endl; CarsNum--;}
void GetColor () { cout<<"Color of the car is"<<color<<endl;}
static int GetCarsNum () {cout<<"Static membet CarsNum="<<CarsNum<<endl; return 0;}
private:
COLOR color;
static int CarsNum;
};
int Car::CarsNum=0;
int main()
{
int (Car::*pfunc) () = NULL;
pfunc=&Car::GetCarsNum ();
Car *ptr= new Car(RED);
ptr->GetColor ();
ptr->GetCarsNum ();
delete ptr;
ptr=0;
Car::GetCarsNum();
return 0;
}
Err msg: 错误消息:
main.cpp|23|error: lvalue required as unary '&' operand
Problem is with: 问题在于:
pfunc=&Car::GetCarsNum ();
Any help would be greatly appreciated 任何帮助将不胜感激
With &Car::GetCarsNum ()
you are calling GetCastNum
, and taking the return value to make it a pointer (with the address-of operator &
). 使用
&Car::GetCarsNum ()
您将调用GetCastNum
,并使用返回值使其成为指针(带有运算符&
的地址)。
To solve this simply drop the parentheses: 要解决此问题,只需删除括号:
pfunc=&Car::GetCarsNum;
No need for parentness: 无需父母身份:
pfunc=&Car::GetCarsNum;
and 和
int (Car::*pfunc) () = NULL;
Oh, UPDATE: you have static method: In this case GetCarsNum() is just a simple function: 哦,更新:您有静态方法:在这种情况下,GetCarsNum()只是一个简单的函数:
int (*pfunc) () = &Car::GetCarsNum;
I think that by putting braces behind the method, you call the method. 我认为通过在方法后面加上括号,您可以调用该方法。 This confuses the compiler.
这使编译器感到困惑。 who now thinks the & operator is used as binary operator.
现在认为&运算符用作二进制运算符的人。 So remove the () and only specify the function name.
因此,删除()并仅指定函数名称。
Thanks, guys. 多谢你们。 Now I see the diffrence between pointers to static method (in this case we use syntaxis as for simple function)
现在,我看到了静态方法的指针之间的差异(在这种情况下,我们将语法用于简单函数)
int (*pfunc) () = &Car::GetCarsNum;
int this case both with '&' and without '&' gives the same result.(and what is the difference). int在这种情况下,带“&”和不带“&”的结果都相同(以及区别是什么)。 and calling it:
并调用它:
pfunc();
And other side - function pointer on standart method: 和另一面-标准方法上的函数指针:
void (Car::*pfunc2) () = NULL;
pfunc2=&Car::GetColor;
and calling it: 并调用它:
(ptr->*pfunc2)();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.