C++ 当派生类的成员被强制转换为基类时,是否可以访问该派生类的成员?
我举了一个简单的例子来说明我的问题。这是基类C++ 当派生类的成员被强制转换为基类时,是否可以访问该派生类的成员?,c++,multithreading,inheritance,polymorphism,backgroundworker,C++,Multithreading,Inheritance,Polymorphism,Backgroundworker,我举了一个简单的例子来说明我的问题。这是基类 #include <mutex> #include <atomic> class Task { public: Task() { Empty.store(true); } std::mutex Access; std::atomic<bool> Empty; virtual void Work() = 0; }; 然后,工作线程将获取第一个任务,将
#include <mutex>
#include <atomic>
class Task
{
public:
Task()
{
Empty.store(true);
}
std::mutex Access;
std::atomic<bool> Empty;
virtual void Work() = 0;
};
然后,工作线程将获取第一个任务,将其从队列中移除,并处理它
while(true)
{
Task *current = Queue.front();
Queue.erase(Queue.begin());
current->Work();
}
这个概念行得通吗?调用
current->Work()
时是否可以访问数据
,即使我处理的是指向基类的指针?是:指向基类的引用/指针可以隐式转换为指向派生类的指针/引用。这正是静态多态性的工作原理:
template<typename T>
struct CRTP_base
{
void execute()
{
static_cast<T*>(this)->f(); //The instance is casted to the known derived class, and we use the derived class function f.
}
};
struct Foo : public CRTP_base<Foo>
{
void f()
{
std::cout << "Wow, compile-time resolved polymorphism!" << std::endl;
}
};
int main()
{
Foo my_foo_instance;
CRTP_base<Foo>& base_reference = my_foo_instance;
base_reference.execute();
};
模板
结构CRTP_基础
{
void execute()
{
static_cast(this)->f();//实例被强制转换为已知的派生类,我们使用派生类函数f。
}
};
struct Foo:public CRTP_base
{
void f()
{
std::cout-Yes这是可行的,欢迎使用多态:)并且您甚至不需要强制转换队列;
。这些转换是隐式的。@jrok这是否意味着我可以从第三方库中获取任何类,从该类继承并覆盖某些函数,将实例化对象强制转换回基类,并让库在不知道的情况下使用它?只要您覆盖虚拟方法,这种转换就有效。如果基类是为(有可以重写的虚拟函数),是的。这就是@MaxBeikirch的全部要点,重写而不是重写
while(true)
{
Task *current = Queue.front();
Queue.erase(Queue.begin());
current->Work();
}
template<typename T>
struct CRTP_base
{
void execute()
{
static_cast<T*>(this)->f(); //The instance is casted to the known derived class, and we use the derived class function f.
}
};
struct Foo : public CRTP_base<Foo>
{
void f()
{
std::cout << "Wow, compile-time resolved polymorphism!" << std::endl;
}
};
int main()
{
Foo my_foo_instance;
CRTP_base<Foo>& base_reference = my_foo_instance;
base_reference.execute();
};