简体   繁体   English

在使用它的类的构造函数中初始化std :: array的大小

[英]Initialise size of std::array in a constructor of the class that uses it

Is it possible to use the std::array<class T, std::size_t N> as a private attribute of a class but initialize its size in the constructor of the class? 是否可以使用std::array<class T, std::size_t N>作为类的私有属性,但是在类的构造函数初始化它的大小

class Router{
    std::array<Port,???> ports; //I dont know how much ports do will this have
public:
    Switch(int numberOfPortsOnRouter){
        ports=std::array<Port,numberOfPortsOnRouter> ports; //now I know it has "numberOfPortsOnRouter" ports, but howto tell the "ports" variable?
    }
}

I might use a pointer, but could this be done without it? 我可能会使用指针,但没有它可以这样做吗?

You have to make your class Router a template class 您必须使您的类Router成为模板类

template<std::size_t N> 
class Router{
    std::array<Port,N> ports; 

...
}

in case you want to be able to specify the size of ports at Router level . 如果您希望能够在Router 级别指定ports大小。 By the way, N must be a constant known from compile time. 顺便说一句, N必须是编译时已知的常量。

Otherwise you need std::vector . 否则你需要std::vector

No, the size must be known at compile time. 不,大小必须在编译时知道。 Use std::vector instead. 请改用std::vector

class Router{
    std::vector<Port> ports;
public:
    Switch(int numberOfPortsOnRouter) : ports(numberOfPortsOnRouter) {
    }
};

The size of an std::array<T, N> is a compile-time constant which can't be changed at run-time. std::array<T, N>是一个编译时常量,在运行时无法更改。 If you want an array with flexible bounds you can use a std::vector<T> . 如果你想要一个具有灵活边界的数组,你可以使用std::vector<T> If the size of your array doesn't change and you somehow know the size from its context, you might consider using std::unique_ptr<T[]> . 如果数组的大小没有改变,并且你以某种方式知道其上下文的大小,你可以考虑使用std::unique_ptr<T[]> It is a bit more light-weight but also doesn't help with copying or resizing. 它的重量更轻,但也无助于复制或调整大小。

std::array is an array of fixed length. std::array是一个固定长度的数组。 Therefore the length must be known at compile time. 因此,必须在编译时知道长度。 If you need an array with dynamic length, you want to use std::vector instead: 如果你需要一个动态长度的数组,你想使用std::vector代替:

class Router{
    std::vector<Port> ports;
public:
    Switch(int numberOfPortsOnRouter):ports(numberOfPortsOnRouter){}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM