BaseクラスとDerivedクラスがあります。一方、STLを使用するListクラスを作成しました。PrintData()
基本クラスには、基本クラスに属する整数を出力する、と呼ばれる仮想関数があります。Derivedクラスでは; 同じ関数printData()
は、Derivedに属する整数と、Baseクラスの他の整数を出力します。
重要なのは、クラスListでは、Derivedインスタンスをリストに挿入したかどうかに関係なく、Baseからデータを取得しているだけです。
ベースデータも含まれているはずの派生データを印刷する必要があります。コードは次のとおりです。
#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の整数であるBaseクラスデータを取得しているだけですが、値が4のDerivedから整数を取得していません。