开发者

Overloading Default Construction with Initializer List

开发者 https://www.devze.com 2022-12-12 05:07 出处:网络
I need to know how to get something to work. I\'ve got a class with a constructor and some constants initialized in the initializer list. What I want is 开发者_运维技巧to be able to create a different

I need to know how to get something to work. I've got a class with a constructor and some constants initialized in the initializer list. What I want is 开发者_运维技巧to be able to create a different constructor that takes some extra params but still use the initializer list. Like so:

class TestClass
{
    const int cVal;
    int newX;
    TestClass(int x) : cVal(10)
    { newX = x + 1; }
    TestClass(int i, int j) : TestClass(i)
    { newX += j; }
}

Totally terrible example, but it gets the point across. Question is, how do I get this to work?


There's no way for one constructor to delegate to another constructor of the same class. You can refactor common code into a static member function, but the latter cannot initialize fields, so you'll have to repeat field initializers in every constructor you have. If a particular field initializer has a complicated expression computing the value, you can refactor that into a static member function so it can be reused in all constructors.

This is a known inconvenience, and a way to delegate to another constructor will be provided in C++0x.


You can't do this in C++03, you'll have to retype the initializer list. This will be fixed in C++0x. Coincidentally, the syntax is exactly what you have, and even more coincidentally the example on Wikipedia is nearly your code. :)


Use C++11's delegate constructor (called at the initialization list location),as following:

SensorObjData::SensorObjData() noexcept : sensor_type_{PerceptionTypes::SensorType::UNKNOWN}, sensor_id_{0U},
                                            is_dirty_{false}, cipv_{0U}, num_obstacles_{0U}, num_lane_markers_{0U},
                                            num_traffic_signs_{0U}, num_traffic_lights_{0U},
                                            num_free_space_border_points_{0U}, num_trans_points_{0U},
                                            timestamp_{0}/*, detection_ready_{false}, segmentation_ready_{false}*/
    {
        data_buf_ptr_ = std::make_shared<std::array<char, kMaxDataLength>>();
    }

    SensorObjData::SensorObjData(std::int64_t timestamp) noexcept : SensorObjData()
    {
        timestamp_ = timestamp;
    }

To summarize: 1. When delegating construct, the initialization list can only have the constructor of the class itself 2. The function body code of the delegated constructor (if any) will run before the delegating constructor body runs.

0

精彩评论

暂无评论...
验证码 换一张
取 消