C++ Array in Header
I am new to C++ so please bear with me.
Basically, I am creating the Header for one of my Classes, and have come into a spot of difficulty.
An instance of the Class in question is created by the Main() function, now when this instance of the Class is created I want to pass in the Array length. However, I cannot do this if it is declared statically in the Header, right?
A开发者_高级运维ny solutions? Sorry, this is probably very simple, but I am coming from a Java background, I'm trying to not do things the Java way.
Thanks.
If you are programming in C++ and are looking to declare an array of variable size, then odds are you don't want to use a "built-in" C style "array". It's sort of a nuts-and-bolts tool.
You probably want to use std::vector
instead. It is a class which is more flexible and does not require a size to be specified at the point of declaration. You can look for tutorials on its use around the web, but here's a random one from Google:
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html#VECTOR
An interesting aspect of C++ is that even though vectors are "library code" and a class you could have potentially written yourself without modifying the compiler, they allow for access with notational conveniences like brackets. Some pros from the faq and some cons from the fqa presented here, take both sides with a grain of salt:
http://yosefk.com/c++fqa/operator.html
While there are some performance benefits to using the bare metal abstraction of a C-style array, std::vector
is almost certainly faster than Java arrays and are a better choice much of the time.
If I understand you correctly, you want to get the size of a statically typed array, and pass it to a class?
If this is correct, have a look at http://ideone.com/JLoZY, it's the first thing that came to my mind.
Basically the compiler will fill in the needed template parameters, so you don't have to worry about them. This can be easily adopted for usage in other scenarios
精彩评论