Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

c++ - different types of objects in the same vector array?

I am using an array in a simple logic simulator program and I want to switch to using a vector to learn it but the reference I am using "OOP in C++ by Lafore" doesn't have a lot about vectors and objects so I am kinda of lost .

Here is the previous code :

gate* G[1000];
G[0] = new ANDgate() ;
G[1] = new ORgate;
//gate is a class inherited by ANDgate and ORgate classes
class gate
{
 .....
 ......
 void Run()
   {   //A virtual function
   }
};
class ANDgate :public gate 
  {.....
   .......
   void Run()
   {
    //AND version of Run
   }  

};
 class ORgate :public gate 
  {.....
   .......
   void Run()
   {
    //OR version of Run
   }  

};      
//Running the simulator using overloading concept
 for(...;...;..)
 {
  G[i]->Run() ;  //will run perfectly the right Run for the right Gate type
 } 

Now what I want to do is

vector(gate*) G;
ANDgate a
G.push_back(a); //Error
ORgate o
G.push_back(o); //Error
for(...;...;...)
{
  G[i]->Run(); //Will this work if I corrected the error ??
}    

so can a vector array hold different types of objects(ANDgate , ORgate) but they inherit the type of the vector array (gate) ????

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're half-way there:

std::vector<gate*> G;
G.push_back(new ANDgate);
G.push_back(new ORgate);
for(unsigned i=0;i<G.size();++i)
{
    G[i]->Run();
}

Of course, this way you need to take care to ensure that your objects are deleted. I'd use a vector of a smart pointer type such as boost::shared_ptr to manage that for you. You could just store the address of local objects (e.g. G.push_back(&a)), but then you need to ensure that the pointers are not referenced after the local objects have been destroyed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...