如何存储多个派生类在一个矢量没有切片
How to store multiple derived classes in a vector without slicing
class Base
{
public :
void func()
{
cout << "Base func()" << endl;
}
};
class DerivedA : public Base
{
public :
void func()
{
cout << "Derived A func()" << endl;
}
};
class DerivedB : public Base
{
public :
void func()
{
cout << "Derived B func()" << endl;
}
};
void main()
{
DerivedA a;
DerivedB b;
vector<shared_ptr<Base>> temp;
temp.push_back(make_shared<DerivedA> (a));
temp.push_back(make_shared<DerivedB> (b));
for(auto ptr : temp)
ptr->func();
}
输出为
Base func()
Base func()
但我期望的是
Derived A func()
Derived B func()
我怎么能把派生类推到基类向量没有切片?如果没有办法解决这个问题,是否有任何等效的方法来存储多个派生类到一个数组,如对象?
没有切片。您需要在Base
中设置func
为虚拟:
virtual void func()
{
cout << "Base func()" << endl;
}
告诉编译器在func
中查找Base*
的动态类型
使func()在基类中为虚函数
class Base
{
public :
virtual void func()
{
cout << "Base func()" << endl;
}
};
你应该使用虚函数。
virtual_functions.h
#pragma once
class Base {
public:
virtual void virtual_func(); // virtual function.
void non_virtual_func(); // non-virtual function.
};
class Derived : public Base {
public:
void virtual_func(); // virtual function.
void non_virtual_func(); // non-virtual function.
};
virtual_functions.cpp
#include "virtual_functions.h"
#include <iostream>
using namespace std;
void Base::virtual_func() {
cout << "Base::virtual_funcn";
}
void Base::non_virtual_func() {
cout << "Base::non_virtual_func()n";
}
void Derived::virtual_func() {
cout << "Derived::virtual_funcn";
}
void Derived::non_virtual_func() {
cout << "Derived::non_virtual_func()n";
}
main.cpp
#include "virtual_functions.h"
int main() {
// Declare an object of type Derived.
Derived aDerived;
// Declare two pointers,
// one of type Derived *
// and the other of type Base *,
// and initialize them to point to derived.
Derived *pDerived = &aDerived;
Base *pBase = &aDerived;
// Call the functions.
pBase->virtual_func(); // Call virtual function.
pBase->non_virtual_func(); // Call nonvirtual function.
pDerived->virtual_func(); // Call virtual function.
pDerived->non_virtual_func(); // Call nonvirtual function.
return 0;
}
输出应该是:
派生:virtual_func ()
基地:non_virtual_func ()
派生:virtual_func ()
派生:non_virtual_func ()
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '