c++ - Private Class Variables -
i having trouble accessing private class variable in 1 of programs. made test program still don't understand i'm doing wrong.
test.h
class test { private: int number; public: int randomize(); };
test.cpp
#include "test.h" #include <iostream> int test::randomize() { number == 1; std::cout << number; return number; }
main.cpp
#include "test.h" #include <stdio.h> int main(int argc, char* argv[]) { test test; int result = test.randomize(); printf ("number = %d", result); return 0; }
i warning when compiling
test.cpp:6:9: warning: expression result unused [-wunused-value] number == 1;
and outputting
134514363number = 134514363
i have no clue going on. thinking outside scope maybe. mean still compiling fine, thought wouldn't able access number @ if wasn't doing right.
any appreciated. thanks
==
comparison operator; returns bool
true
if operands equal.
=
assignment operator; assigns right operand left 1 , returns first operand (as lvalue).
so, number == 1
telling compiler "check if number
equal 1 (and discard result of such comparison)"; notice compiler warning - says you have expression without side-effects result discarded, useless instruction , "suspect" (hence warning).
what want, instead, number = 1
, i.e. "set number
1".
in other words, problem here never assigning definite value number
in code (because misspelled =
), , number
remains @ "indefinite" value (which, in program, happens 134514363, due garbage left on stack crt initialization routines).
Comments
Post a Comment