#include<iostream>
#include <thread>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
class base
{
public:
virtual void fun_1() { cout << "base-1\n"; }
virtual void fun_2() { cout << "base-2\n"; }
};
class derived : public base
{
public:
void fun_1() { cout << "derived-1\n"; }
void fun_2() { cout << "derived-2\n";
}
};
class caller
{
private:
base *p;
derived obj1;
p = &obj1;
public:
void me()
{
std::thread t(std::bind(&base::fun_2, p), this);
t.join();
}
};
int main()
{
caller c;
c.me();
return 0;
}
我写了一个非常简单的线程和多态示例。我要做的就是从另一个包含另一个类对象的类中调用派生函数。该程序无法编译消息p does not name a type
,但我不明白为什么。
答案 0 :(得分:1)
您的错误所在:
p = &obj1;
最好这样写,应该有帮助:
class caller
{
private:
derived obj1;
base *p = &obj1;
......
};
或在构造函数中初始化指针:
class caller
{
private:
derived obj1;
base *p = nullptr;
caller() : p(&obj1) {}
......
};