我有两个类,Base
包含虚拟方法,D
包含该方法的重载。我想创建一个Base
类型的变量,而不是在那里传递继承了D
类的Base
类。这是我的实现:
#include <iostream>
#include <vector>
#include <memory>
#include <cstdio>
#include <fstream>
#include <cassert>
#include <functional>
class Base {
public:
virtual void bar() { std::cout << "B::bar\n"; }
//virtual ~Base() = default;
};
typedef Base* Maker();
Maker* arr[10];
class D : Base
{
public:
D() { std::cout << "D::D\n"; }
~D() { std::cout << "D::~D\n"; }
void bar() override { std::cout << "D::bar\n"; }
};
template <class T>
Base* make(){
return new T;
}
int main()
{
std::unique_ptr<Base> p1(new D);
p1->bar();
//arr[0] = make<D>();
return 0;
}
顺便说一句,它正在使用结构,但是当我尝试通过类来实现它时,我会得到错误。
最佳答案
D
私有(private)地继承自B
。因此,D*
不能转换为B*
。您可能需要class D : public Base { ... };