0

Hej! I want to learn using pointers to functions in C. So I write me a little calculator witch contains private operation's functions and one pointer to switch trough them based on entered operation sign. I don't know if it is going to be more efficient then calling individual functions but it just a test.

So this function, inside of Calculator class public section, suppose to set POper pointer to appropriate operation:

 void Calculate() {
    switch (m_s) {
    default:
      printf("Error, wrong operation sign\n");
      break;
    case '+':
      POper = &Calculator::Add;
      break;
    case '-':
      POper = &Calculator::Sub;
      break;
    case '*':
      POper = &Calculator::Multi;
      break;
    case '/':
      POper = &Calculator::Divide;
      break;
    }
  }

When I try to compile fallowing code gcc gives me this type incorrectness warring:

../src/main.cpp: In member function ‘void Calculator::Calculate()’:
../src/main.cpp:16:13: error: cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment
       POper = &Calculator::Add;
             ^
../src/main.cpp:19:13: error: cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment
       POper = &Calculator::Sub;
             ^
../src/main.cpp:22:13: error: cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment
       POper = &Calculator::Multi;
             ^
../src/main.cpp:25:13: error: cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment
       POper = &Calculator::Divide;

I don't really understand, both POper and use members are part of Calculator class. What it means with cannot convert ‘float (Calculator::*)()’ to ‘float (*)()’ in assignment? Whats the difference?

  • "POper" type is "float ( * )()" but you are assigning a "‘float (Calculator::*)()". Solution: Change "POper" type to "‘float (Calculator::*)()". BTW, you are writing C++ program. There is no class in C. Change the tag. – MayurK Oct 26 '16 at 05:09
  • Thank you! But when I try to save the value to a variable, `m_sum = (*POper)`, i get an error: `../src/main.cpp:28:15: error: invalid use of unary ‘*’ on pointer to member m_sum = (*POper);`. Can you please help me with that? –  Oct 26 '16 at 05:21
  • What is the type of "m_sum"? And what is the expected output? – MayurK Oct 26 '16 at 05:45
  • `m_sum` is a float. And output is result of simple calculation function like add or divide. I just add it at the and of `Calculate()` function to save the result. –  Oct 26 '16 at 06:15
  • You have use function pointer as if it is a function. Your call should be like this: "m_sum = POper();". – MayurK Oct 26 '16 at 12:34
  • I find out that I need to use `this` pointer. Such syntax fix the problem: `m_sum = (this->*POper)();`. Info: http://www.newty.de/fpt/fpt.html#call. –  Oct 26 '16 at 15:19

0 Answers0