c++ - 使用 std::thread 从派生类调用重写方法

标签 c++ c++11 polymorphism

我正在尝试让这样的东西工作:

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;
}

我想要的结果是:

this is derived1.

问题是它甚至无法编译。我正在使用 VisualStudio 2013。

错误是:

Error 2 error C3640: 'main::Base::[thunk]: __thiscall main'::2'::Base::`vcall'{0,{flat}}' }'' : a referenced or virtual member function of a local class must be defined

有什么想法可以实现吗?

编辑:澄清一下,我想在线程中做的事情更复杂,这只是我程序结构的一个例子(所以 lambda 对我来说不是个好主意)

最佳答案

您的代码很好,除了两点:

std::thread(&Base::print, *this);

应该是:

std::thread(&Base::print, this).join(); // join & no asterisk

关于c++ - 使用 std::thread 从派生类调用重写方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25568825/

相关文章:

C++11 似乎不可能通过 shared_ptr 访问 protected 成员

c++ - 正在写入 &str[0] 缓冲区(std :string) well-defined behaviour in C++11?

c++ - 在 C++ 中使用多态性访问类的孙子类

c++ - 使用 QWT 和 Microsoft Visual C++ 2010 绘制 MatLab 等效图

c++ - 静态库和共享库的区别?

c++ - 将任何函数作为模板参数传递

c++ - "type-switch"在 C++11 中构造

haskell - 模式匹配后多态性丢失

c++ - Sets/Maps 迭代器不可递增

c++ - 自定义构建文件更改不会触发 VS 2017 中的项目重建