Calling a method from one class in another class

时间:2017-08-05 11:40:12

标签: c++ class methods

I have this class:

boer.h

#pragma once
#include <functional>
#include <iostream>

class boer
{
private:

    std::function<void(int id_)> someFun;

public:
    boer();
    ~boer();

    void setSomeFun(std::function<void(int id_)> someFun_);

    void getSomeFun();
};

boer.cpp

#include "boer.h"

boer::boer() { }

boer::~boer() { }

void boer::setSomeFun(std::function<void(int id_)> someFun_)
{
    someFun = someFun_;
}

void boer::getSomeFun()
{
    someFun(12345);
}

And this class:

aircraft.h

#pragma once
#include <functional>
#include <iostream>
#include "boer.h"

class aircraft
{
private:

    boer Boer;

public:
    aircraft();
    ~aircraft();

    void source_forSomeFun(int id_);
};

aircraft.cpp

#include "aircraft.h"

aircraft::aircraft() { }

aircraft::~aircraft() { }

void aircraft::source_forSomeFun(int lol_)
{
    std::cout << "AMAZING!!!" << std::endl;
}

And I need to connect void source_forSomeFun(int id_); in aicraft with std::function<void(int id_)> someFun; in boer. How can I do this? Maybe there is another way, but i think this method is the most preferable.

int main()
{
    aircraft Aircraft;
    boer Boer;

    Boer.setSomeFun(???); // here

    Boer.getSomeFun();

    int i;
    std::cin >> i;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

Boer.setSomeFun([&](int v){aircraft.source_forSomeFun(v);});

Use a lambda.