简体   繁体   中英

pointers to derived members of the class

if I have for example some class Base and derived from it Derived Also I have some list of shared pointers:

list<shared_ptr<Base> > list

I create shared pointer:

line 5    shared_ptr<Derived> ptr(new Derived(//some constructor));

my question is, can I do something like this:

list.push_back(ptr);

if Yes, can somebody explain why can I recieve an error (I receive this on the line 5)

no matching function for call to //here It writes me my constructor to Derived

thanks in advance for any help

my question is, can I do something like this: list.push_back(ptr);

Yes - your problem has nothing to do with inheritance or smart pointers - you simply don't have the constructor declared you are trying to use.

A simple example that reproduces the error is:

struct X {};
X x(1);

Which gives you:

no matching function for call to ' X::X(int) '

You fix that by either constructing the instance differently or by adding the missing constructor:

struct X { X(int) {} };

You are trying to assign a value of type shared_ptr<Derived> to a container of shared_ptr<Base> . Try assigning pointer to Derived to shared_ptr<Base> and then adding that to the list<>:

class BASE {
 public:
  BASE() { }
  const char *name() const { return nameImpl(); }
 private:
  virtual const char *nameImpl() const { return "BASE"; }
};

class DERIVED : public BASE {
 public:
  DERIVED() { }
 private:
  virtual const char *nameImpl() const { return "DERIVED"; }
};


int main() {

 list< shared_ptr< BASE > > baseSequence;

 shared_ptr< BASE > basePtr(new BASE);
 baseSequence.push_back( basePtr );
 basePtr.reset(new DERIVED);
 baseSequence.push_back( basePtr );

 shared_ptr< DERIVED > derivedPtr(new DERIVED);
 baseSequence.push_back( derivedPtr ); 

 BOOST_FOREACH(const shared_ptr< BASE > &ptr, baseSequence) {
  cout << ptr->name() << "\n";
 }
 return 0;
}

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM