我有一个带有Derived1和Derived2派生类的基类以及一个Consumer类。

我想用两个派生类对象创建一个基指针 vector ,然后传递给使用者类,以便它可以使用以下方法获取派生类详细信息

pointervec.at(0).i

我已经为此坚持了很长时间,无法使其正常工作。这是我所拥有的简化版本。我担心围绕创建 vector ,将其传递到线程并访问不同索引的语法。
#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();
}

最佳答案

为了使您的示例正常工作,需要纠正一些错误。

  • 由于Consumer::doStuff是一个非静态成员函数,因此需要Consumer实例才能对其运行。
  • 由于上述原因,Consumer需要定义的构造函数
  • doStuff的签名需要采用Base指针的 vector (对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();
    }
    

    关于c++ - 将派生类指针的 vector 传递给线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37704024/

    10-12 18:50