c++ - 模板类初始化的问题
PHP中文网
PHP中文网 2017-04-17 14:17:43
0
1
350
#include <cstddef>

template <class T, size_t N>
struct block
{
    typedef T value_type;
    typedef value_type* pointer;
    typedef value_type& reference;
    typedef const value_type& const_reference;
    typedef ptrdiff_t diffrence_type;
    typedef size_t size_type;
    typedef pointer iterator;
    typedef const pointer const_iterator;
    iterator begin() { return data;}
    iterator end() { return data + N;}
    const_iterator begin() const { return data;}
    const_iterator end() const { return data + N;}
    reference operator[](size_t n) { return data[n];}
    const_reference operator[](size_type n) const { return data[n];}
    size_type size() const { return N;}
    T data[N];
};

int main()
{
    block<int, 6> A = {1, 4, 2, 8, 5, 7};
    return 0;
}

在main函数里,对这个变量进行了初始化。书上说,以这种方式初始化,必须符合某种限制:struct 不能拥有使用者声明的任何constructo,也不能拥有任何private或protected member。block是满足这些限制的,那么为什么满足了这些限制后,就可以以这种方式去初始化结构体里面的数组?

PHP中文网
PHP中文网

认证0级讲师

reply all(1)
洪涛

In C++, the initialization methods of structures and classes are exactly the same.
If the structure or class does not have member variables other than public and does not provide a constructor, then you can use the {} method for initialization.
If there are member variables of private or protected, or a constructor is provided, the constructor must be used for initialization.

As for why this array can be initialized in this way, it is because there is only one member variable here, which is the array data.
block<int, 6> A = {1, 4, 2, 8, 5, 7};The more standardized way of writing this sentence is
block<int, 6> A = {{1, 4, 2, 8, 5, 7}};.
You can add a T data[N] before T* p and try again, but it won’t work.

Because {} is initialized in order, and the array in the class is actually multiple elements of the same type put together, so it can be initialized in order, and there is no need to add any more A {} came and was placed inside.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template