我有一个带有Derived1和Derived2派生类的基类和一个Consumer类。
我想创建一个带有两个派生类对象的Base指针向量,然后传递给使用者类,以便它可以使用
获取派生类的详细信息pointervec.at(0).i
我多年来一直坚持这一点,无法让它发挥作用。这是我所拥有的简化版本。我关注创建向量的语法,将其传递给线程并访问不同的索引。
#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();
}
答案 0 :(得分:4)
为了让你的例子有用,有一些错误需要纠正。
Consumer::doStuff
是非静态成员函数,因此您需要Consumer
的实例来运行它。Consumer
需要定义的构造函数doStuff
的签名需要Base
指针的引用(引用a),而不是Base
个对象t3
需要将Consumer
的实例作为其第一个转发参数(以提供this
参数。最终工作代码:
#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();
}