gcc - Fail to push_back() derived class into STL list in C++ -


i appreciate this.

the problem can not push_back stl list. here details:

fo abstract class , foo class inherit fo. f0, f1 instances of class foo. foolist has type std::list<foo> , folist has type std::list<fo*>.

when try foolist.push_back(f1); can cout value member p, can not call function test(); when try folist.push_back(&f1); can not cout value member p, let alone call function test().

with lines error-1/2/3 commented, obtained output:

fo constructor foo constructor fo constructor foo initialization  fo constructor foo copy constructor inside foolist :11 ------------------------ 

i realize folist.push_back(&f1) did not call foo copy constructor, may relevant error-2.

when try call function test() in foolist, obtain error msg:

error: member function 'test' not viable: 'this' argument has type   'const foo', function not marked const 

when try cout member p in folist, obtain error msg:

error: no member named 'p' in 'fo' 

i have no idea how fix problem.

thanks lot!

full code list below:

#include <iostream> #include <list>  class fo { public:     fo() { std::cout << "fo constructor" << std::endl; }     fo(const fo& f) { std::cout << "fo copy constructor" << std::endl; }     virtual ~fo(){};     virtual void test()=0; };  class foo : public fo { public:     int p;     foo() { std::cout << "foo constructor" << std::endl; }     foo(int p_): p(p_) {std::cout << "foo initialization " << std::endl;};     foo(const foo& f) { this->p = f.p; std::cout << "foo copy constructor" << std::endl; }     virtual void test() {std::cout<<"testing foo ... "<<std::endl;} };  int main() {     foo f0,f1(11);      std::list<foo> foolist;     std::list<foo>::const_iterator i=foolist.begin();     foolist.push_back(f1);i++;     std::cout << "inside foolist :" << i->p << std::endl;     //std::cout<<"inside foolist :"<<i->p<<" , "<<i->test();  // error-1     std::cout << "------------------------" << std::endl;      std::list<fo*> folist;     std::list<fo*>::const_iterator it=folist.begin();     folist.push_back(&f1);it++;     //std::cout<<(*it)->p<<std::endl;  // error-2     //std::cout<<"inside folist :"<<(*it)->p<<" , "<<it->test();  // error-3      return 0; } 

to fix

//std::cout<<"inside foolist :"<<i->p<<" , "<<i->test();  // error-1 

change

std::list<foo>::const_iterator i=foolist.begin(); 

to

std::list<foo>::iterator i=foolist.begin(); 

to fix

//std::cout<<(*it)->p<<std::endl;  // error-2 

replace with

std::cout<<(foo*(*it))->p<<std::endl;  // error-2 

to fix:

//std::cout<<"inside folist :"<<(*it)->p<<" , "<<it->test();  // error-3 

replace

//std::cout<<"inside folist :"<<(foo*(*it))->p<<" , "<<it->test();  // error-3 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -