c++11 - 'shared_ptr 没有可行的转换' 到 'shared_ptr'
问题描述
我的任务是创建一个 Circuit Sim,但在尝试使用 NotGate 类时遇到了问题。
组件是一个抽象类。
class Component
{
public:
virtual bool getOutput() = 0;
virtual void prettyPrint(string padding) = 0;
virtual void linearPrint() = 0;
};
然后我有 Pin 和 NotGate,它们通过组件的依赖关系继承。
class Pin {
private:
bool value;
string label;
public:
Pin::Pin(string theLabel) {
label = theLabel;
}
bool Pin::getOutput() {
return value;
}
void Pin::setValue(bool newVal) {
this->value = newVal;
}
};
class NotGate {
private:
shared_ptr<Component> input;
public:
NotGate::NotGate() {
input = make_shared<Component>();
}
bool NotGate::getOutput() {
if (input == 0) {
return true;
} else {
return false;
}
}
void NotGate::setInput(shared_ptr<Component> in) {
this->input = in;
}
};
我创建了一个 Pin "c" 和一个 notGate "n1",我希望将 "c" 作为 "n1" 的输入。当我尝试使用命令执行此操作时:
n1->setInput(c);
它告诉我:No viable conversion from 'shared_ptr<Pin>' to 'shared_ptr<Component>s'
我尝试创建一个新的 shated_ptr 组件和一堆不起作用的不同东西。
解决方案
来自编译器的错误消息很清楚。如果您希望能够在预期ashared_ptr<Pin>
时使用 a,您应该创建一个 的子类。从抽象的角度来看,对我来说,成为.shared_ptr<Component>
Pin
Component
Pin
Component
class Pin : public Component
{
...
};
推荐阅读
- javascript - 为范围内的每个单元格添加值(Google 应用程序脚本)
- angular - 等待 openDialog 总是返回错误的 Angular 材质
- javascript - Node.js:express + promise-mysql 返回
- c# - HttpClient.SendAsync 从 api 接收响应的时间比预期的要长
- algorithm - 计算一个圆上的一组点可以组成的四边形的数量
- react-native - 从不同的屏幕更新状态值
- c# - 使用 Bresenham 的线算法从路径中检索所有 gps 坐标
- python-3.x - 在 Python 3 中将列表字符串化回列表
- c# - 当 x != 1 和 y != 0 时 x * y == y 可以吗?
- microservices - 通信微服务/微前端架构