没有从 Singleton 到嵌套 Listener 的可行转换 *

No viable conversion from Singleton to nested Listener *

无法在网站上的其他地方找到解决方案,但如果我错了,请指出其他地方。

假设我想听一个按钮并根据它的大小从单例对象做一些事情...

我会创建一个带有嵌套侦听器的按钮对象...

class ScaledButton
{
public:
    ScaledButton(const int buttonSize) : _buttonSize(buttonSize){}

    ~ScaledButton(){}

    /** Nested Listener calss*/
    class Listener
    {
    public:
        virtual ~Listener() {}

        /** Would be called on button click for example... */
        virtual void scaledButtonChanged(const int buttonSize) = 0;
    };

    void addListener (Listener* listener)
    {
        _listener = listener;
    }

private:
    ScaledButton();
    int _buttonSize;
    Listener* _listener; ///< POINTER TO THE LISTENER
};

然后创建我的从监听器公开继承的单例...

class Singleton : public ScaledButton::Listener ///< PUBLIC INHERITANCE HERE
{
public:
    static Singleton& getInstance()
    {
        static Singleton instance;
        return instance;
    }

    virtual void scaledButtonChanged(const int buttonSize) override
    {
        //... do something depending on the size of the button!!!!!!
    }

private:
    Singleton(){} // Must call get instance.
    Singleton(const Singleton&); // Cannot copy
    void operator= (const Singleton& args); // Cannot copy
};

然后像这样在 main 中添加监听器..

int main()
{
    Singleton& mySingleton = Singleton::getInstance();

    ScaledButton myButton(5);
    myButton.addListener(mySingleton); ///< ERROR HERE!

    return 0;
}

但是无法添加侦听器并出现错误:

*没有从 'Singleton' 到 'ScaledButton::Listener '

的可行转换

我的直觉是,它与使用带引用的单例和带指针的 Listener 的冲突有关:或者纯虚拟 Listener 的继承 class。

尽管尝试了各种单例实现(例如使用全局 ptr),但我的 C++ 技能还不足以解决错误。有什么建议么?

在 Mac OS 使用 clang 编译器。

你需要一个指针,所以获取你的对象的地址:

myButton.addListener(&mySingleton); 

如果您有其他语言的背景,您需要阅读更多关于 C++ 中的引用与值语义的信息。