在C ++中找出一个结构

时间:2018-01-20 22:13:48

标签: c++ data-structures struct constructor

我正在做“生命游戏”作为大学的任务,导师给了我们部分代码,但是我有理解两个部分的问题。

第一:

grid(int scale) : scale_(scale), width_(problem_definition::width(scale)), height_(problem_definition::height(scale)), data_(new problem_definition::data_type[width_*height_]) 

直到我能理解他要求用于模拟网格的存储器的那一刻。但是,我无法掌握新的语法。为什么那些括号空格?网格后的冒号(int scale)是什么意思?

第二

void initialize()
{
for (std::size_t y = 0; y < height_; ++y)
{
    for (std::size_t x = 0; x < width_; ++x)
    {
        at(x,y) = problem_definition::initialize(x, y, scale_);
    }
}

}

第二个for循环中的“at()”是什么?

我很感激这里有任何见解是完整的结构定义:

struct grid
{
  grid(int scale) : scale_(scale), width_(problem_definition::width(scale)), height_(problem_definition::height(scale)), data_(new problem_definition::data_type[width_*height_])
{

}
void initialize()
{
    for (std::size_t y = 0; y < height_; ++y)
    {
        for (std::size_t x = 0; x < width_; ++x)
        {
            at(x,y) = problem_definition::initialize(x, y, scale_);
        }
    }
}
problem_definition::data_type at(std::size_t x, std::size_t y, int dx, int dy)
{
    if (dx<0 && -dx>x) return problem_definition::out_of_bounds_value();
    if (dy<0 && -dy>y) return problem_definition::out_of_bounds_value();
    if (x + dx >= width_) return problem_definition::out_of_bounds_value();
    if (y + dy >= height_) return problem_definition::out_of_bounds_value();
    return at((int)x + dx, (int)y + dy);
}
problem_definition::data_type& at(std::size_t x, std::size_t y)
{
    return data_[x + y*width_];
}
void swap(grid& other)
{
    std::swap(scale_, other.scale_);
    std::swap(width_, other.width_);
    std::swap(height_, other.height_);
    std::swap(data_, other.data_);
}
void print(std::ostream& str)
{
    for (std::size_t y = 0; y < height_; ++y)
    {
        for (std::size_t x = 0; x < width_; ++x)
        {
            str << at(x, y);
        }
        str << std::endl;
    }
}
private:
 int scale_;
 std::size_t width_;
 std::size_t height_;
 std::unique_ptr<problem_definition::data_type[]> data_;
};

1 个答案:

答案 0 :(得分:1)

让我们在第一行添加一些空白区域,以便于阅读:

grid(int scale) : scale_(scale),
                  width_(problem_definition::width(scale)),
                  height_(problem_definition::height(scale)),
                  data_(new problem_definition::data_type[width_*height_]) 

现在我们可以很容易地看到冒号(:是冒号,;是分号)定义初始化列表,该列表采用一系列var(value)对并分配每个{每个value {1}}。{/}

我没有看到任何带有空格的&#34;括号&#34;所以不能回答这个问题。但是var以外只是形式的标准数组类型:new。元素类型为element_type[length],数组的长度为problem_definition::data_typewidth_

最后,height_只是一个返回引用的函数调用。如果你研究函数定义:

at()

然后你可以通过引用的魔力看到调用problem_definition::data_type& at(std::size_t x, std::size_t y) { return data_[x + y*width_]; } 的行与以下内容相同:

at()
相关问题