c++ 如何在原始摘要 class 中创建一个接受派生 class 输入的函数
c++ how to make a function which takes an input of a derived class, within the original abstract class
假设我有一个名为 Turtle 的抽象 class。在 class 中,我在自己的线程上有一个函数,它接受 Turtle 的输入。
编译器说我不能使用抽象类型 Turtle 的输入。
我想要发生的是函数接受派生 class 的输入,而不是抽象的 Turtle class。我应该如何解决这个问题?
#include <thread>
class Turtle
{
std::thread T_thread;
public:
virtual void foo(Turtle T) = 0;
//tried making this virtual as well
void do_stuff(Turtle T)
{
foo(T);
}
Turtle()
{
T_thread = std::thread(do_stuff, this);
}
};
如果Turtle
是一个抽象数据类型那么你不能声明这个类型的变量。但是你可以声明一个变量,它的数据类型是一个指针或者指向这个类型的引用。
在方法的签名中使用对 Turtle
的引用:
void do_stuff(Turtle &T)
传递给do_stuff
的实际参数的动态类型永远不能是Turtle
类型,因为它是抽象的,但它可以是从[=派生的类型11=](如果导出的 class 也不是抽象的)。
假设我有一个名为 Turtle 的抽象 class。在 class 中,我在自己的线程上有一个函数,它接受 Turtle 的输入。 编译器说我不能使用抽象类型 Turtle 的输入。 我想要发生的是函数接受派生 class 的输入,而不是抽象的 Turtle class。我应该如何解决这个问题?
#include <thread>
class Turtle
{
std::thread T_thread;
public:
virtual void foo(Turtle T) = 0;
//tried making this virtual as well
void do_stuff(Turtle T)
{
foo(T);
}
Turtle()
{
T_thread = std::thread(do_stuff, this);
}
};
如果Turtle
是一个抽象数据类型那么你不能声明这个类型的变量。但是你可以声明一个变量,它的数据类型是一个指针或者指向这个类型的引用。
在方法的签名中使用对 Turtle
的引用:
void do_stuff(Turtle &T)
传递给do_stuff
的实际参数的动态类型永远不能是Turtle
类型,因为它是抽象的,但它可以是从[=派生的类型11=](如果导出的 class 也不是抽象的)。