#include <iostream>
#include<vector>
using namespace std;
class A{
private:
int x,y;
public:
A(int x=0,int y=0){
this->x=x;
this->y=y;
}
//输出x y
void fun(){
cout<<x<<","<<y<<endl;
}
};
class B{
private:
vector<A*> objvec; // 利用迭代器
public:
B(){}
void add(A *t){
objvec.push_back(t);
}
void show(){
vector <A *>::iterator ivec;
for(ivec=objvec.begin();ivec<objvec.end();ivec++){
(*ivec)->fun();
}
}
//逐一释放每个
~B(){
vector<A *>::iterator ivec;
for(ivec=objvec.begin();ivec<objvec.end();ivec++){
delete *ivec;
}
}
};
int main(int argc, char** argv) {
B *pB=new B();
// 没有new 但是利用了析构
pB->add(new A(3,5));
pB->add(new A(7,8));
pB->add(new A(9,11));
pB->show();
return 0;
}
第一个和第二个程序有点差异运行结果一样
#include <iostream>
#include<vector>
using namespace std;
class A{
private:
int x,y;
public:
A(int x=0,int y=0){
this->x=x;
this->y=y;
}
//输出x y
void fun(){
cout<<x<<","<<y<<endl;
}
};
class B{
private:
vector<A*> objvec; // 利用迭代器
public:
B(){}
void add(A *t){
objvec.push_back(t);
}
void show(){
vector <A *>::iterator ivec;
for(ivec=objvec.begin();ivec<objvec.end();ivec++){
(*ivec)->fun();
}
}
int main(int argc, char** argv) {
A *pA1=new A(3,5);
A *pA2=new A(7,8);
A *pA3=new A(9,11);
B *pB=new B();
pB->add(pA1);
pB->add(pA2);
pB->add(pA3);
pB->show();
delete pA1;
delete pA2;
delete pA3;
delete pB;
return 0;
}
#include <iostream>
using namespace std;
class A{
private:
int x,y; //数据成员xy
A *next; // 基类指针
public:
A(int x,int y,A *t){
this->x=x;
this->y=y;
next=t;
}
virtual void fun(){ //纯虚函数
cout<<x<<","<<y<<endl;
if(next)
next->fun();
}
};
class A1:public A{
public:
A1(int i,int j,A *n):A(i,j,n){}
};
class A2:public A{
public:
A2(int i,int j,A *n):A(i,j,n){}
};
class A3:public A{
public:
A3(int i,int j,A *n):A(i,j,n){}
};
int main(int argc, char** argv) {
A3 *p3=new A3(7,8,NULL);
A2 *p2=new A2(5,6,p3);
A *p =new A1(3,4,p2);
p->fun();
delete p3;
delete p2;
delete p;
return 0;
}
#include <iostream>
using namespace std;
class A{
private:
int x,y; //数据成员xy
A *next; // 基类指针
public:
A(int x,int y,A *t){
this->x=x;
this->y=y;
next=t;
}
virtual void fun()=0; //纯虚函数
void gun(){
cout<<x<<","<<y<<endl;
if(next)
next->fun();
}
};
class A1:public A{
public:
A1(int i,int j,A *n):A(i,j,n){}
void fun(){
cout<<"调用A1的函数"<<endl;
gun(); //回基类
}
};
class A2:public A{
public:
A2(int i,int j,A *n):A(i,j,n){}
void fun(){
cout<<"调用A2的函数"<<endl;
gun(); //回基类
}
};
class A3:public A{
public:
A3(int i,int j,A *n):A(i,j,n){}
void fun(){
cout<<"调用A3的函数"<<endl;
gun(); //回基类
}
};
int main(int argc, char** argv) {
A3 *p3=new A3(7,8,NULL);
A2 *p2=new A2(5,6,p3);
A *p =new A1(3,4,p2);
p->fun();
delete p3;
delete p2;
delete p;
return 0;
}