如何将依赖关系反转原理实现为单例模式

问题描述 投票:0回答:1

所以我在做单例类,我想服从依赖性反转原理,但是当函数承诺基本接口时,编译器不允许我返回派生实例。

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"
    }
...
}

有没有办法使它起作用,还是我被迫放弃这个想法?

c++ interface singleton solid-principles
1个回答
0
投票

这是因为您要返回派生类引用,请尝试返回基类引用

class IElevatorHandler{
public:

...

    static ElevatorHandler& get() {
        static ElevatorHandler instance;
        return instance; 
    }
...
}
© www.soinside.com 2019 - 2024. All rights reserved.