简体   繁体   中英

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?

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

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 .

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) {
    }
};

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.

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){}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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