首页 > 解决方案 > '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 组件和一堆不起作用的不同东西。

标签: c++11inheritanceshared-ptr

解决方案


来自编译器的错误消息很清楚。如果您希望能够在预期ashared_ptr<Pin>时使用 a,您应该创建一个 的子类。从抽象的角度来看,对我来说,成为.shared_ptr<Component>PinComponentPinComponent

class Pin : public Component
{
   ...
};

推荐阅读