将C++函数从类传递到另一个类对象,而不是从main传递

llew8vvj  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(156)

我有一个叫CoffeeShop的类和另一个叫user的类。我想从CoffeeShop类传递一个函数给user类,但是出现了一个错误,我尝试做的是
用户类别:

class user {
public:
    function<void (string)> fun;
    string name;
    void order_coffee() {
        fun(name);
    }
};

然后是咖啡店课程

class CoffeeShop {
public:
    mutex mtx;
    void Make_Coffee(string name) {
        cout << "in queue: " << name << endl;
        unique_lock<mutex> lock(mtx);
        cout << "welcome,order in process, " << name << endl;
        this_thread::sleep_for(chrono::seconds(4));
        cout << "good bye, " << name << endl;
        lock.unlock();
    }

    void assign() {
        user a;
        a.fun = CoffeeShop::Make_Coffee;
        a.name = "amr kamal";
        thread th1(&user::order_coffee, a);

        user b;
        b.fun = a.fun;
        b.name = "hadeer";
        thread th2(&user::order_coffee, b);

        th2.join();
        th1.join();
    }
};

我使用分配的函数开始运行函数,我想做的是让用户使用make_coffee函数并在队列中等待,它一个接一个地处理,我希望能够让用户访问函数。
我主要按如下方式使用该类

int main() {
   CoffeeShop coffeeShop;
   coffeeShop.assign();
}

我得到的错误是关于分配用户make_coffee函数

error C2679: binary '=': no operator found which takes a right-hand operand of type 'void (__cdecl CoffeeShop::* )(std::string)' (or there is no acceptable conversion)
tf7tbtn2

tf7tbtn21#

你有两个选择
1.将其 Package 在lambda a.fun = [this](string line) {this->Make_Coffee(line);};
1.使用std::mem_fun
您面临的问题是std::function需要知道 * this *。还有Why is "using namespace std;" considered bad practice?

相关问题