Hello, This part of the code is from something bigger so that is why it is overly complicated. Basically I want to have the numbers 0-9 readout in order with out repeating anything. Here is the code
What is returned is 0-9 but each digit is repeated 20 times. To test this problem I commented out the whole test function so that it was a void function that did nothing and it still returned 0-9 with each digit is repeated 20 times. I feel like I am missing some fundamental thing. Thanks for any help.
This code will just print a random number (since you forgot to initialize z) and do nothing else.
If you comment out the code in Test(), the program does nothing at all.
When you post a code snippet from a larger program, make sure the problem actually happens with it.
When you say initialize you simply mean int z=0; ( just saying z=0) right?
Well when i do that my compiler gives me the errors:
-forbids initialization of member `z',
-making `z' static ,
-forbids in-class initialization of non-const static member `z'
Class data members cannot be initialized in the same way as ordinary variables. Instead, they must be initialized by the constructors initialization list, like this:
1 2 3 4 5
class Class
{
Class( ) : Z( 0 )
{ }
};
Note the colon after the parameter list of Class's constructor. This is the initialization list of Class::Class( ). However, assigning n to Class::Z is assignment, not initialization. Either way, a variable/data member must be given a value before it's used.
Do you mean static in the C sense -- as in only visible to the "current compilation unit" (i.e. .cpp file plus all the header it includes) => nope, but you can make an instance of a class static in thise sense.
Or the class sense? => yes. The following declares a static data member for class Class -- which means that all instances of Class see the same value of Z. These cannot be initialized using the constructor's initializer list.
1 2 3 4 5 6 7 8 9
// class.h
class Class
{
public:
Class ();
staticint Z;
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// class.cpp
#include <iostream>
// and the other usual suspects
usingnamespace std;
#include "class.h"
int Class::Z = 0;
int main()
{
cout << "Z = " << Class::Z << endl;
return 0;
}