Aug 18, 2012 at 8:22pm UTC
For simplicity sake, I am trying to declare
char x = 'X'
.
in a private section of my class.
I cannot do this, because I cannot declare a variable in the header file. How do I make char x = 'X' for every function in the class?
Last edited on Aug 18, 2012 at 8:34pm UTC
Aug 18, 2012 at 8:25pm UTC
Set the value of x in the constructor(s).
Last edited on Aug 18, 2012 at 8:26pm UTC
Aug 18, 2012 at 8:26pm UTC
try declaring it as:
const char x='X'
idk if it will work, but if it doesn't just add it to the constructor.nevermind, it did not work Also note the single quotes.
Last edited on Aug 18, 2012 at 8:39pm UTC
Aug 18, 2012 at 8:37pm UTC
Script, sorry I meant single quoted. But if I try to declare
const int x = 'X'
in the header it says
error: ISO C++ forbids initialization of member 'x'
and if I do this:
Header
1 2
private :
const char x;
.cpp
1 2 3 4
(CONSTRUCTOR)
{
const char x = 'X' ;
}
it gives me
error: uninitialized member 'Player::x' with 'const' type 'const char'|
Last edited on Aug 18, 2012 at 8:38pm UTC
Aug 18, 2012 at 8:38pm UTC
You declare a local variable x in the constructor that will be destroyed at once after executing of the constructor. You should initialize data member of the class x.
1 2 3 4
Player::Player()
{
x = 'X' ;
}
Or you can initialize it in mem initializer list
Player::Player() : x( 'X' ) {}
The class definition
1 2 3 4 5 6 7 8 9 10 11 12
class Player
{
public :
Player();
void ex();
protected :
private :
char x;
};
Last edited on Aug 18, 2012 at 8:43pm UTC
Aug 18, 2012 at 8:41pm UTC
Vlad, you mean make another class just for setting char x = 'X'?
Aug 18, 2012 at 8:43pm UTC
I mean your class because you are changing it every time.
Last edited on Aug 18, 2012 at 8:44pm UTC
Aug 18, 2012 at 8:45pm UTC
Ah I forgot about the member initializer list. Thank you!
Is this the only way to declare variables that can be used throughout the entire class?
Aug 18, 2012 at 8:47pm UTC
You can declare a global variable but it is a bad practice.
Aug 18, 2012 at 8:55pm UTC
That works too. Thank you!
Is there a way to do this with an array?
Aug 18, 2012 at 8:57pm UTC
Yes, you can to do that with an array.
Aug 18, 2012 at 9:01pm UTC
For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
struct A
{
int a[3] = { 1, 2, 3 };
};
int main()
{
A a;
for ( auto x : a.a ) std::cout << x << ' ' ;
return 0;
}
However not all compilers support this code.
In your code example the array shall be defined as having two elements and with specifier
constexpr
static constexpr char x[2] = {'X' , 'Y' };
Last edited on Aug 18, 2012 at 9:06pm UTC
Aug 18, 2012 at 9:03pm UTC
Ok this is great! Thanks!