-
variables never change~
Hi all, please search my code first:
#include <iostream>
#include <string>
class character
{
public:
void showX();
private:
int x;
};
void character::showX()
{
x=0;
cout << x << endl;
x++;
cout << x << endl;
}
void main()
{
character black;
black.showX();
black.showX();
}
finally, output shows:
0 1
0 1
it seems the x is initialized after being invoked a second time. it looks a bit like const not variable here, and it confused me much, what cause it be ???:confused:
-
>and it confused me much, what cause it be ???
Your question confuses me much, what is the problem? Every time showX is called, x is set to 0, printed, incremented, and then printed again. Aside from your ghastly use of undefined behavior, this is correct and predictable.
Code:
#include <iostream>
#include <string>
class character
{
public:
void showX();
private:
int x;
};
void character::showX()
{
x=0;
/* Note that I had to change calls to cout,
** cin, and endl to include the namespace prefix
** since you don't have a using statement. I
** also changed the first call to cout so that it
** ends with a space to create the exact output
** from your post.
*/
std::cout << x << ' ';
x++;
std::cout << x << std::endl;
}
// void main is wrong, main returns an int.
int main()
{
character black;
black.showX();
black.showX();
}
--------
Output:
0 1
0 1
Could you be more specific as to what output you were expecting?
-Prelude
-
if you are expecting to get 0 and 1 the first time you call the showX() function and 1 and 2 the second time, then heres your problem. the x variable being private is only used by the showX function. the first time you run through it you set x to 0, cout that, then increment it and cout that. that gives you 0 1. now, if you run it again, it sets x to 0 via the first statement in the function, and couts that, then increments, then couts again. so, if you wanted it to show up 0 1 the first time then 1 2 the second time, make the int x public not private...that will work if you use the same class for your code in the main function. otherwise you should create a new version of showX that returns x. next time be clear on your question
-
soooooooooooooooooooooooooooory everyone, I found that it was some mistakes of my own, now it is solved, Cheers~:D