所以我在做单例类,我想服从依赖性反转原理,但是当函数承诺基本接口时,编译器不允许我返回派生实例。
class IElevatorHandler{
public:
...
static IElevatorHandler& get() {
static ElevatorHandler instance;
return instance; // E0434 : C++ a reference of type "IElevatorHandler&" (not const-qualified) cannot be initialized with a value of type "ElevatorHandler"
}
...
}
有没有办法使它起作用,还是我被迫放弃这个想法?
这是因为您要返回派生类引用,请尝试返回基类引用
class IElevatorHandler{
public:
...
static ElevatorHandler& get() {
static ElevatorHandler instance;
return instance;
}
...
}