| snig (14) | |
|
I have to questions the 1st is: How can i initialize an array after declaring it. for example string test[5] then somewhere else in the program how can i do something like this test ??? = {"one", "Two", "three", "Four", "Five"}; my 2nd question is: how can i initialize variable within a class. any help is greatly appreciated | |
|
|
|
| closed account (jw6XoG1T) | |||
|
well with the array, you would have to do something along the lines of: test[0] = "One"; test[1] = "Two"; test[2] = "Three; etc... to initialize a variable within a class, the most common way that i find people do it is within the classes contructor. So take the following code for example:
so as you can see in the above code there are two ways to initialize variables that you declare within a class. The first method is within the constructors brackets and using the "this" keyword (it's optional to use the keyword though, personally i use it) and setting the variables to their appropriate values. The second method is by initializing the variables outside the function definitions name using a colon, and typing the variables name followed by the value of it inside parenthesis. | |||
|
|
|||
| snig (14) | |
| thanks so much that makes a lot of sence :) i was hoping there would be away to initialize the whole array but oh well. one question now is how could i access the variable age inside of main. thanks again | |
|
|
|
| clanmjc (661) | ||||||
Then in main.
| ||||||
|
|
||||||
| kempofighter (1120) | |
|
After declaring an array, you can only assign to it. Initialization must happen during the declaration if at all. Another option is to use a functor, when that makes sense along with an algorithm such as std::generate. Take a look at this. http://cplusplus.com/reference/algorithm/generate/ | |
|
|
|
| JLBorges (1336) | |||
> How can i initialize an array after declaring it
| |||
|
Last edited on
|
|||