c++ - Vector in an abstract class
问题描述
I believe that the question here is similar however I still need more clarification on it.
Let's say I create a vector inside an abstract class (which stores objects of another class). How would I be able to use .pushback() from another class if I can't initialise an object of an abstract class?
Obviously the easiest solution is to put the vector in another class but I need another way. I've read you can do this by storing pointers to those objects in a vector. But can somebody give me an example please?
解决方案
The purpose of an abstract class is to provide an interface that is then implemented in concrete derived classes.
If you want to push items onto the vector which is a data member of the abstract class, then create an appropriate derived class and then you can create an instance of that derived class, which will thus contain a vector you can add entries to.
class Base{
public:
virtual void do_stuff()=0; // this is an abstract base class
protected:
std::vector<int> data;
};
class Derived: public Base
{
public:
void do_stuff() {
// concrete implementation
data.push_back(42); // can add values to vector inherited from base class
}
};
int main()
{
Derived d;
d.do_stuff(); // will add entries to d.data
}
However, I wonder if that is really what you are trying to achieve.
推荐阅读
- regex - 正则表达式匹配来自 .txt 文件的 IP
- python - python中对象的方法和属性有什么区别?
- java - 如何在Spring中通过ApplicationContext即时直接使用bean
- amazon-web-services - AWS EC2 phpMyAdmin 在允许 httpd.conf 文件中的 html 目录权限后停止工作
- node.js - forEach 中的 forEach 打印 nodejs mongodb 中 else 语句的双重结果
- db2 - 如何在 db2 中显示隐藏表?表已成功创建,但未显示在数据库中
- amazon-web-services - aws ecr get-login --region us-east-1 命令失败。
- unix - 如何从列到行获取唯一值
- angular - PrimeNg V.7 FullCalendar View Crash
- android - 此应用将受到管理 SMS 和 CALL_LOG 权限使用的 Google Play 政策变更的影响