#include <iostream>
#include <vector>
using namespace std;
class shape{
public:
virtual void draw(){
cout << "draw a shape" << endl;
}
void func(){
cout << "call func" << endl;
}
};
class squareness:public shape{
virtual void draw(){
cout << "draw a squareness" << endl;
}
};
class circleness:public shape{
virtual void draw(){
cout << "draw a circleness" << endl;
}
};
int main(){
//1.基类指针 2.virtual function
vector<shape*> v(3);
v[0]=new shape();
v[1]=new squareness();
v[2]=new circleness();
for (auto p:v){
p->draw();
}
return 0;
}
C++ 在 vector 中存储不同类型的对象
最新推荐文章于 2024-07-11 09:11:19 发布
本文介绍了一个C++编程示例,通过Shape基类和Squareness、Circleness派生类展示面向对象的继承与多态。通过vector存储不同类型的shape指针并调用virtual draw()方法,展示了动态绑定的概念。
摘要由CSDN通过智能技术生成