简体   繁体   中英

Calling another constructor C++

I have something like this:

Foo::Foo(vector<item> items) {
    // do stuff
}

I'd like to call this constructor from another constructor:

Foo::Foo(char* buf, size_t num) {
    // unpack the bytes into vector
    Foo::Foo(items);
}

Is this possible in C++ 17+? I know that you can call another constructor using an initialize list, but this seems trickier

Simply call a delegating constructor. Use a helper function to construct the vector<item> .

namespace {
vector<item> helper(char*buff, size_t num)
{
    /* your implementation for re-packaging the data here */
}
}

Foo::Foo(char*buff, size_t num)
  : Foo(helper(buff,num))
{}

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