使用std :: thread从派生类调用overriden方法

Dor*_*hua 3 c++ polymorphism c++11

我想尝试这样的事情:

int main()
{
    class Base
    {
    public:
        Base() = default;
        virtual void print() = 0;
        void CallThread()
        {
            std::thread(&Base::print, *this);
        };
    };

    class derived1 : public Base
    {
    public:
        derived1() = default;
        void print() { printf("this is derived1\n"); }

    };
    class derived2 : public Base
    {
    public:
        derived2() = default;
        void print() { printf("this is derived2\n"); }

    };
    Base* ptr;
    ptr = new derived1();
    ptr->CallThread();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想要的结果是:

这是派生的1.

问题是它甚至不会编译.我正在使用VisualStudio 2013.

错误是:

错误2错误C3640:'main :: Base :: [thunk]:__ thiscall main'::2':: Base ::`vcall'{0,{flat}}'}'':本地类的引用或虚拟成员函数必须被定义

任何想法如何使这项工作?

编辑:为了清楚,我在线程中尝试做的更复杂,这只是我的程序结构的一个例子(所以lambda对我来说不是一个好主意)

Pio*_*cki 10

你的代码很好,除了两件事:

std::thread(&Base::print, *this);
Run Code Online (Sandbox Code Playgroud)

应该:

std::thread(&Base::print, this).join(); // join & no asterisk
Run Code Online (Sandbox Code Playgroud)