我必须创建从抽象类继承的类的实例。我的代码很简单。它应该基于抽象类创建对象类的实例。抽象类也是模板类。然后,我需要将此对象放入保存指向该对象的指针的存储类中。传递指针时出现错误:
templates.cpp: In member function ‘void storage::setPTR(std::unique_ptr<child>&)’:
templates.cpp:39:28: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = child; _Dp = std::default_delete<child>]’
this->childPTR = pointer;
^
In file included from /usr/include/c++/5/memory:81:0,
from templates.cpp:3:
/usr/include/c++/5/bits/unique_ptr.h:357:19: note: declared here
unique_ptr& operator=(const unique_ptr&) = delete;
^
templates.cpp: In function ‘int main()’:
templates.cpp:45:30: error: type/value mismatch at argument 1 in template parameter list for ‘template<class _Tp, class _Dp> class std::unique_ptr’
std::unique_ptr<INTERFACE> p = std::make_unique<child>("xxx");
^
templates.cpp:45:30: note: expected a type, got ‘INTERFACE’
templates.cpp:45:30: error: template argument 2 is invalid
templates.cpp:45:65: error: cannot convert ‘std::_MakeUniq<child>::__single_object {aka std::unique_ptr<child>}’ to ‘int’ in initialization
std::unique_ptr<INTERFACE> p = std::make_unique<child>("xxx");
^
templates.cpp:48:24: error: ‘newChild’ was not declared in this scope
testStorage.setPTR(newChild);
^
我的代码:
#include <iostream>
#include <string>
#include <memory>
// using namespace std;
template<typename type1, typename type2, typename type3> class INTERFACE {
protected:
type1 x;
type2 y;
type3 name;
public:
virtual type1 setX(type1 x) = 0;
virtual type2 setY(type2 y) = 0;
};
class child : public INTERFACE<int, float, std::string> {
public:
child(std::string z) {
this->name = z;
}
virtual int setX(int x) override {
this->x = x;
}
virtual float setY(float y) override {
this->y = y;
}
};
class storage {
private:
std::unique_ptr<child> childPTR;
public:
void setPTR(std::unique_ptr<child> & pointer) {
this->childPTR = pointer;
}
};
int main(){
// std::unique_ptr<INTERFACE> newChild(new child("xxx"));
std::unique_ptr<INTERFACE> p = std::make_unique<child>("xxx");
storage testStorage;
testStorage.setPTR(newChild);
return 0;
}
我做错了什么?
std::unique_ptr
不可复制分配。它是可移动分配的。因此,请在参数和std::move
中使用值传递setPTR
。
您需要提供一个具体的类型,而不是模板:
std::unique_ptr<INTERFACE<int, float, std::string>> p =
std::make_unique<child>("xxx");
声明newChild
,在这种情况下,您将再次需要将std::move
其放入函数或发出该变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句