使用类方法实现std :: thread时出错

问题描述 投票:0回答:1

我编写了一个简单的类myshape,其中有一个名为display_area()的类方法,用于打印N的矩形区域,其中N将由用户提供。我希望这个函数独立地在一个线程中运行。然而,在实现线程时,我得到错误说

error: invalid use of non-static member function  
        std::thread t1(s.display_area, 100);

我已经看到相关的讨论C++ std::thread and method class!其中对象实例已作为指针创建,与我的情况不同,无法解决我的问题。我在下面附上我的代码以供参考。任何帮助表示赞赏。

#include <iostream>
#include <thread>
using namespace std;

class myshape{
  protected:
    double height;
    double width;
  public:
    myshape(double h, double w) {height = h; width = w;}
    void display_area(int num_loop) {
      for (int i = 0; i < num_loop; i++) {
        cout << "Area: " << height*width << endl;
      }
    }
};

int main(int argc, char** argv) 
{
  myshape s(5, 2);
  s.print_descpirtion();
  std::thread t1(s.display_area, 100);
  t1.join();
}
c++ stdthread
1个回答
0
投票

首先,实例永远不会“创建为指针”。有时实例是动态分配的(默认情况下,此机制会为您提供一个指向播放的指针)。但是,即使它们不是,它们仍然有一个地址,你仍然可以得到一个代表该地址的指针。

我们使用std::thread的构造函数的方式与您希望调用其成员函数的对象的存储持续时间无关。

所以,的确,你应该遵循同样的指示:

std::thread t1(&myshape::display_area, &s, 100);

(这个函数的cppreference页面上有an example of exactly this。)

作为一个混乱的奖励点,这个构造函数还允许你传递一个引用而不是一个指针,所以如果你对它更熟悉,下面也会做得很好:

std::thread t1(&myshape::display_area, s, 100);
© www.soinside.com 2019 - 2024. All rights reserved.