【发布时间】:2018-07-01 16:08:43
【问题描述】:
我必须创建从抽象类继承的类的实例。
我的代码真的很简单。它应该基于抽象类创建对象类的实例。抽象类也是模板类。然后我需要将此对象放入storage 类中,该类包含指向该对象的指针。就这样。这项任务是某种家庭作业。
甚至可以基于抽象类创建类的实例吗?
如果是 - 我做错了什么? 如果没有 - 我怎样才能让它相似?
#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() = 0;
virtual type2 setY() = 0;
};
class child : public INTERFACE<int, float, std::string> {
public:
child(std::string z) {
this->name = z;
}
int setX(int x) {
this->x = x;
}
float setY(float y) {
this->y = y;
}
};
class storage {
private:
std::shared_ptr<child> childPTR;
public:
void setPTR(const std::shared_ptr<child> & pointer) {
this->childPTR = pointer;
}
};
int main(){
std::shared_ptr<child> newChild(new child("xxx"));
storage testStorage;
testStorage.setPTR(newChild);
return 0;
}
编译错误:
templates.cpp: In function ‘int main()’:
templates.cpp:44:52: error: invalid new-expression of abstract class type ‘child’
std::shared_ptr<child> newChild(new child("xxx"));
^
templates.cpp:18:7: note: because the following virtual functions are pure within ‘child’:
class child : public INTERFACE<int, float, std::string> {
^
templates.cpp:14:23: note: type1 INTERFACE<type1, type2, type3>::setX() [with type1 = int; type2 = float; type3 = std::__cxx11::basic_string<char>]
virtual type1 setX() = 0;
^
templates.cpp:15:23: note: type2 INTERFACE<type1, type2, type3>::setY() [with type1 = int; type2 = float; type3 = std::__cxx11::basic_string<char>]
virtual type2 setY() = 0;
【问题讨论】:
-
使用
overridespecifier。你会发现它很有启发性。特别是()和(int x)没有声明相同的参数列表。 -
另外,标题是什么?
-
很抱歉。误点击。应该是:
Instance of class which inherits from abstract class -
你试图一次做太多新的事情。当您尝试实现新功能时,请单独处理它们,在它们完美运行之前不要将它们组合起来。
-
然后edit您的帖子并将标题更正为应该是。
标签: c++ templates inheritance abstract-class