我有一个基类和一个派生类;另一方面,我做了一个使用STL的List类。基类有一个名为PrintData()
的虚拟函数,它打印属于Base类的整数。在派生类中;相同的函数printData()
将打印一个属于Derived的整数,另一个来自Base类。C++在STL列表上打印数据
问题是,在类List中,我只是从Base获取数据,无论我是否在列表中插入Derived实例。
我需要打印派生数据,也应该有基本数据。 下面是代码:
#pragma once;
#include <iostream>
#include <sstream>
using namespace std;
class Base{
protected:
int x;
public:
Base(){
x=3;
}
void setX(int a){
x=a;
}
int getX(){
return x;
}
virtual string printData(){
stringstream f;
f<<getX()<<endl;
return f.str();
}
};
class Derived : public Base{
int a;
public:
Derived(){
this->Base::Base();
a=4;
}
void setA(int x){
a=x;
}
int getA(){
return a;
}
string printData(){
stringstream a;
a<<getA()<<getX()<<endl;
return a.str();
}
};
这里是List类:
#pragma once;
#include "Prueba.cpp"
#include <list>
class Lista{
list<Base*> lp;
public:
Lista(){
}
void pushFront(Base* c){
lp.push_front(c);
}
void pushBack(Base* c){
lp.push_back(c);
}
void printList(){
list<Base*>::const_iterator itr;
for(itr=lp.begin(); itr!=lp.end(); itr++){
cout<<(*itr)->printData();
}
}
~Lista(){
}
};
int main(){
Derived* d=new Derived();
Lista* l=new Lista();
l->pushFront(d);
l->printList();
system("Pause");
return 0;
}
我刚开始的基类的数据,这是与3 但我的值的整数“M不衍生自具有的4
不需要调用'Base :: Base',编译器自动为你做这件事。基类构造函数总是出现在派生类构造函数之前。 –
这似乎工作,当我尝试它。你确定你在编译和运行正确的东西吗? –