c++ - 如何从基类指针向量调用派生类函数?
问题描述
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
class A {
private:
int v1;
public:
void setv1(int v1) { this->v1 = v1; }
int getv1() { return v1; }
virtual void print() { cout << v1 << endl; }
};
class B : public A {
private:
int v2;
public:
void setv2(int v2) { this->v2 = v2; }
int getv2() { return v2; }
void print() {
A::print();
cout << v2 << endl;
}
};
int main() {
vector<A *> vect;
B *b = new B();
vect.push_back(b);
vect.at(0)->setv2(5);
}
我目前正在学习继承。我想调用如图所示的 setv2 函数,但是当我这样做时,向量中的对象不再识别它。有没有办法让我拥有一个基类指针向量并允许其中的派生类调用它们的函数?
解决方案
推荐阅读
- java - 无法在自定义 gradle 插件实现中使用外部依赖项
- amazon-web-services - 您可以为 sns 电子邮件添加样式吗?
- azure - Azure 函数批处理大小
- angular - 失去焦点Angular表单时验证错误消失
- python - 如何修复 python 3 中的“无效编码”错误?
- android - 处理构建变体中的微小差异
- sql - SQl 服务器转换为日期失败,日期时间有效
- c# - 我想获得 Stex.com API 访问令牌
- c - 我应该如何推断 x86-64 机器上 addb 指令的 C 数据类型?
- windows - windows上vscode中的julia可执行路径