也许这是一个简单的问题,因为我还是C ++的新手。我想使用某种工厂来封装我的应用程序中的日志记录。这个想法是只有工厂知道哪个具体类将处理函数调用。应用程序将始终调用基本日志记录类的抽象接口。
工厂方法应如下所示:
std::unique_ptr<AbstractLoggingClass> Factory::getDefaultLogger(const std::string& param){
return new ConcreteLoggingClass(param);
}
ConcreteLoggingClass
是AbstractLoggingClass
的子类。
但是我收到以下错误:
Error: could not convert '(operator new(64ul), (<statement>,
((ConcreteLoggingClass*)<anonymous>)))' from 'ConcreteLoggingClass*'
to 'std::unique_ptr<AbstractLoggingClass>'
我的问题是我不知道如何实例化ConcreteLoggingClass
并将unique_ptr
返回AbstractLoggingClass
我已经找到了this post,但我仍然没有看到解决方案。
答案 0 :(得分:12)
你想要的std::unique_ptr
构造函数是explicit
,因此你需要......好吧......明确它。尝试
return std::unique_ptr<AbstractLoggingClass>(new ConcreteLoggingClass(param));
答案 1 :(得分:8)
如果您可以使用C ++ 14,则应使用>>> l=['Facebook;Google+;MySpace', 'Apple;Android']
>>> new1 = l[0].split(';')
>>> new1
['Facebook', 'Google+', 'MySpace']
>>> new2= l[1].split(';')`enter code here`
>>> new2
['Apple', 'Android']
>>> totalnew = new1 + new2
>>> totalnew
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
:
std::make_unique
否则明确创建return std::make_unique<ConcreteLoggingClass>( param );
:
std::unique_ptr
答案 2 :(得分:1)
std::unique_ptr<T>
的构造函数是explicit
。它不会从指针隐式转换,因为这样做意味着指针被静默删除。
您可以返回std::unique_ptr<T>
明确构建它,例如:
return std::unique_ptr<AbstractLoggingClass>(new ConcreteLoggingClass(param));
答案 3 :(得分:1)
您无法将指针转换为unique_ptr
,您必须创建它:
std::unique_ptr<AbstractLoggingClass> Factory::getDefaultLogger(const std::string& param){
return std::unique_ptr<AbstractLoggingClass>(new ConcreteLoggingClass(param));
}
答案 4 :(得分:1)
如果您有c ++ 14或更高版本:
std::unique_ptr<AbstractLoggingClass>
Factory::getDefaultLogger(const std::string& param)
{
return std::make_unique<ConcreteLoggingClass>(param);
}