Initialize static class member with an instance of a derived class if type is a reference to a pure virtual base class
当我尝试通过
1 | ILogger & Action::m_activeLogger = DefaultLogger(); |
编译器(C ++ 11 + Linux)说:
cannot bind non-const lvalue reference of type"ILogger &" to an rvalue of type ILogger
如何初始化指向实例的静态成员变量?
最小示例:
我有一个接口基类(纯虚拟)
base.h:
1 2 3 4 5 | class ILogger { public: virtual ~ILogger(); virtual void write(std::string msg); } |
使用DefaultLogger.h作为实现的派生类(此处未显示CPP文件):
1 2 3 4 5 | class DefaultLogger : public ILogger { public: ~DefaultLogger(); void write(std::string msg); } |
在Action.h中,我使用静态成员变量并引用了基类:
1 2 3 4 | class Action { static ILogger & m_activeLogger; // getter/setter to register another logger... } |
如何使用派生类初始化静态成员变量
记录器不是通过引用存储的,而是用
1 2 3 4 | class Action { static std::unique_ptr<ILogger> m_activeLogger; // getter/setter to register another logger... } |
然后应该有一个访问器来获取它:
1 | ILogger& get_instance(){return * m_activeLogger;} |
否则,您将无法设置其他记录器! 至少没有参考。
旁注,虚拟调用可能应该对字符串使用const&,然后用
1 | void write(const std::string& msg) override; |