On 18 Dec 2005 02:19:48 -0800, "vo******@gmail.com"
<vo******@gmail.com> wrote:
How do you keep a value in a member function ?
i mean ...
void main ()
{
int a =0;
change(a);
change(a);
}
void change(int a)
{a++
cout << a ;
}
output should be 1 and 2;
i forgot how you keep a value in a function :p
greets
If you want to change the variable's value, you must pass it by
reference as someone else has already shown you. However, there are
some other things worth pointing out:
1. "Member functions" are functions which are defined as part of a
class definition. You use no classes in your code except for
std::ostream (i.e. std::cout) which is defined in the STL library.
Your change() and main() are global, or stand-alone functions.
However, the same advice to pass the int by reference would equally
apply to a member function.
2. The main() function must return int, not void, in order to be a
proper C++ program. You can leave out a return statement, though, in
which case the compiler will generate code to return the value 0 from
your main() function back to the operating system shell or process
from which it was invoked.
3. You need a semicolon after "a++" inside the change() function.
4. If main() is defined before change(), you must provide a
forward-declaration of change() in order to be able to call it inside
of main().
5. In order to use cout, you must include the appropriate standard
header <iostream> (without an .h).
6. Also, you must provide access to the namespace std in order to use
cout, either by writing a using directive, a using declaration, or by
explicitly qualifying the name: std::cout.
Older compilers might let you get away with your present code WRT
items 2 and 6, but it isn't standards-conforming code and should be
corrected.
Good luck learning C++ ... it is an exciting adventure!
--
Bob Hairgrove
No**********@Home.com