如何通过构造函数初始化所有对象

How do you go about initializing all the objects by the constructor?

本文关键字:对象 初始化 何通过 构造函数      更新时间:2023-10-16

如何通过构造函数初始化所有对象?

假设在Location类中有4个Set对象。如何初始化构造函数中的4个set对象以设置为默认对象?我试图首先创建已经初始化的对象:

设置nyX(nyXv);然后尝试将其放入构造函数中,但这不会起作用。

class Location
{
public:
    vector<int> nyXv = { 0, 1, 2, 3, 4, 5};
    vector<int> nyYv = { 0, 1, 2, 3, 4, 5 };
    vector<int> sfXv = { 6, 7, 8, 9, 10 };
    vector<int> sfYv = { 6, 7, 8, 9, 10 };

    Set nyX;
    Set nyY;
    Set sfX;
    Set sfY;

    Location();
    ~Location();
};

class Set
{
public:
    Set(vector<int> &);
};

您应该使用一个初始化列表:

Location::Location()
  : nyX(nyXv)
{}