Reputation: 3
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
Upvotes: 0
Views: 89
Reputation: 3
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). and calling it:
pfunc();
And other side - function pointer on standart method:
void (Car::*pfunc2) () = NULL;
pfunc2=&Car::GetColor;
and calling it:
(ptr->*pfunc2)();
Upvotes: 0
Reputation: 181
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.
Upvotes: 0
Reputation: 409136
With &Car::GetCarsNum ()
you are calling GetCastNum
, and taking the return value to make it a pointer (with the address-of operator &
).
To solve this simply drop the parentheses:
pfunc=&Car::GetCarsNum;
Upvotes: 2
Reputation: 1297
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:
int (*pfunc) () = &Car::GetCarsNum;
Upvotes: 1