簡體   English   中英

在使用它的類的構造函數中初始化std :: array的大小

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

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

...
}

. 如果您希望能夠在Router 指定ports大小。 順便說一句, N必須是編譯時已知的常量。

否則你需要std::vector

不,大小必須在編譯時知道。 請改用std::vector

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

std::array<T, N>是一個編譯時常量,在運行時無法更改。 如果你想要一個具有靈活邊界的數組,你可以使用std::vector<T> 如果數組的大小沒有改變,並且你以某種方式知道其上下文的大小,你可以考慮使用std::unique_ptr<T[]> 它的重量更輕,但也無助於復制或調整大小。

std::array是一個固定長度的數組。 因此,必須在編譯時知道長度。 如果你需要一個動態長度的數組,你想使用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