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

2023-12-09

是否可以使用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?
    }
}

我可能会使用指针,但是如果没有它可以完成吗?


你必须让你的课Router模板类

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

...
}

如果您希望能够指定大小ports at Router级别。顺便一提,N必须是编译时已知的常量。

否则你需要std::vector.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在使用 std::array 的类的构造函数中初始化 std::array 的大小 的相关文章