[英]Pass vector of derived class pointers to thread
I have a Base class with Derived1 and Derived2 derived classes and a Consumer class. 我有一个带有Derived1和Derived2派生类的基类以及一个Consumer类。
I want to create a vector of Base pointers with the two derived class objects to then pass to the consumer class so it can get derived class details using 我想用两个派生类对象创建一个基指针向量,然后传递给使用者类,以便它可以使用以下方法获取派生类详细信息
pointervec.at(0).i
I've been stuck on this for ages and cannot get it to work. 我已经坚持了很长时间,无法使其正常工作。 This is a simplified version of what I have.
这是我所拥有的简化版本。 I'm concerned about the syntax around creating the vector, passing it to the thread and accessing different indexes.
我担心围绕创建向量,将其传递到线程并访问不同索引的语法。
#include<vector>
#include<thread>
#include<iostream>
using namespace std;
class Base
{
public:
Base() {};
void dosomething() {cout<<i<<endl;}
int i;
};
class Derived1 : public Base
{
public:
Derived1() {i = 5;}
};
class Derived2 : public Base
{
public:
Derived2() {i = 10;}
};
class Consumer
{
public:
Consumer();
void dostuff( vector<Base> &pointervec) {cout<<5<<endl;}
};
int main( int argc, char ** argv )
{
Derived1 derived1;
Derived2 derived2;
vector<Base*>pointervec;
pointervec.push_back(&derived1);
pointervec.push_back(&derived2);
std::thread t1(&Derived1::dosomething, &derived1);
std::thread t2(&Derived2::dosomething, &derived2);
std::thread t3(&Consumer::dostuff, ref(pointervec));
t1.join();
t2.join();
t3.join();
}
To make your example work, there are a few mistakes that need to be corrected. 为了使您的示例正常工作,需要纠正一些错误。
Consumer::doStuff
is a non-static member function, you need an instance of Consumer
to run it on. Consumer::doStuff
是一个非静态成员函数,因此您需要一个Consumer
实例来对其运行。 Consumer
needs a defined constructor Consumer
需要定义的构造函数 doStuff
needs to take a (reference to a) vector of Base
pointers, not Base
objects doStuff
的签名需要采用(指向) Base
指针(而不是Base
对象)的向量 t3
needs said instance of Consumer
as its first forwarded parameter (to provide the this
parameter. t3
需要Consumer
所述实例作为其第一个转发参数(以提供this
参数)。 Final working code: 最终工作代码:
#include<vector>
#include<thread>
#include<iostream>
using namespace std;
class Base
{
public:
Base() {};
void dosomething() {cout<<i<<endl;}
int i;
};
class Derived1 : public Base
{
public:
Derived1() {i = 5;}
};
class Derived2 : public Base
{
public:
Derived2() {i = 10;}
};
class Consumer
{
public:
Consumer() {}
void dostuff( vector<Base*> &pointervec) {cout<<pointervec.at(0)->i<<endl;}
};
int main( int argc, char ** argv )
{
Derived1 derived1;
Derived2 derived2;
Consumer c;
vector<Base*>pointervec;
pointervec.push_back(&derived1);
pointervec.push_back(&derived2);
std::thread t1(&Derived1::dosomething, &derived1);
std::thread t2(&Derived2::dosomething, &derived2);
std::thread t3(&Consumer::dostuff, &c, ref(pointervec));
t1.join();
t2.join();
t3.join();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.