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

半腔热情 提交于 2019-12-12 07:27:35

问题


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?

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?


回答1:


No, the size must be known at compile time. Use std::vector instead.

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



回答2:


You have to make your class Router a template class

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. By the way, N must be a constant known from compile time.

Otherwise you need std::vector.




回答3:


The size of an std::array<T, N> is a compile-time constant which can't be changed at run-time. If you want an array with flexible bounds you can use a 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[]>. It is a bit more light-weight but also doesn't help with copying or resizing.




回答4:


std::array is an array of fixed length. Therefore the length must be known at compile time. If you need an array with dynamic length, you want to use std::vector instead:

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


来源:https://stackoverflow.com/questions/13103219/initialise-size-of-stdarray-in-a-constructor-of-the-class-that-uses-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!