Error passing a method to another method. C ++

1

I'm a beginner in programming and decide to venture into a project with friends, in which I need the program to descend on the order of the routine based on one factor, I'm moving to a smaller chained list to facilitate the organization and have to deal with whole class. However I am finding problem to pass the method to function. Here is an example code:

#include <iostream>
#include <string>

using namespace std;

class Txt
{
    string palavra;
    int tam;
public:
    void load(string txt) { palavra = txt; tam = txt.length(); }
    void print() { cout << palavra << endl; };
    int w_tam() { return tam; }
};

class Info2
{
public:
    int tam;
    void (*print)();
};

Info2 redirecionar(Txt txt)
{
    Info2 info;
    info.tam = txt.w_tam();
    info.print = &(txt.print); // aqui acontece um erro
    return info;
}

int main()
{
    Txt A, B;
    A.load("Amor");
    B.load("Bolota");

    Info2 AA, BB;
    AA = redirecionar(A);
    BB = redirecionar(B);

    if (AA.tam > BB.tam)
    {
        AA.print();
    }
    else
    {
        BB.print();
    }
}

I use VS2017, and error has the following description: '& invalid operation on the associated member function expression. But I could not understand it, I saw the same idea in another topic in C.

    
asked by anonymous 27.12.2017 / 05:28

1 answer

1

The type of Txt::print is not void (*)() , but void (Txt:: *)() .

Change type of print in class Info2 :

class Info2
{
public:
    int tam;
    void (Txt:: *print)();
};

And assign the member function address:

info.print = &Txt::print;

Also save the instance of a Txt , since a member function can only be called with a valid instance of the class.

To call the member function, use operator .* (or ->* if the instance of Info2 is accessible only by a pointer) along with the instance of a Txt :

auto print = AA.print;
(A.*print)(); // Ou (A.*AA.print)();

Note the parentheses around A.*print : the precedence of a function call is greater than the .* operator, so the parentheses are required.

If you want to avoid this syntax and do not mind dynamic allocations, you can use std::function to save the method call inside a lambda:

#include <functional>

class Info2
{
public:
    int tam;
    std::function<void()> print;
};

Info2 redirecionar(Txt &txt)
{
    Info2 info;
    // ...
    info.print = [&txt] { txt.print(); };
    // ...
}

// ..
AA.print();
    
27.12.2017 / 20:06