-2

我在我的一个程序中访问私有类变量时遇到问题。我做了这个测试程序,但仍然不明白我做错了什么。

测试.h

class Test
{
private:
    int Number;
public:
    int Randomize();
};

测试.cpp

#include "test.h"
#include <iostream>

int Test::Randomize()
{
    Number == 1;
    std::cout << Number;
    return Number;
}

主文件

#include "test.h"
#include <stdio.h>

int main(int argc, char* argv[])
{
    Test test;
    int result = test.Randomize();
    printf ("Number = %d", result);
    return 0;
}

编译时收到此警告

test.cpp:6:9: warning: expression result unused [-Wunused-value]
        Number == 1;

它正在输出

134514363Number = 134514363

我不知道发生了什么。认为我可能超出了它的范围。但我的意思是它仍然编译得很好,我想如果我做得不对,我根本无法访问 Number。

任何帮助,将不胜感激。谢谢

4

5 回答 5

3

== is the equality operator, that checks two operands for equality. = is the assignment operator, that places the value of its right operand's evaluation in the left operand.

It is giving you a warning (not compiler error) to indicate that Number == 1; is not used to do anything, which is very likely to be a mistake of the programmer (e.g. it's asking if you meant to use = instead?)

Finally, the reason why you get 134514363 is because in C and C++, if you don't set a variable to anything, it has a random value that you can't predict, based on whatever happened to be in memory there. Basically, C/C++ doesn't initialize variables when they're declared.

In general, compiler warnings are worth reading - they usually mean mistakes in your program.

于 2013-05-21T02:04:11.240 回答
3

== is the comparison operator; it returns a bool that is true if the operands are equal.

= is the assignment operator; it assigns the right operand to the left one and returns the first operand (as an lvalue).

So, with Number == 1 you are telling the compiler "check if Number is equal to 1 (and discard the result of such comparison)"; notice that the compiler is warning you about this - he says you that you have an expression without side-effects whose result is discarded, which is obviously a useless instruction and thus "suspect" (hence the warning).

What you want, instead, is Number = 1, i.e. "set Number to 1".

In other words, the problem here is that you are never assigning a definite value to Number in your code (because you misspelled =), and Number remains at an "indefinite" value (which, in your program, happens to be 134514363, probably due to the garbage left on the stack by the CRT initialization routines).

于 2013-05-21T02:06:12.263 回答
2

此行使用equality运算符,其结果被丢弃,因此发出警告:

Number == 1;

应该使用=which 是一个assignment运算符:

Number = 1;
于 2013-05-21T02:04:01.617 回答
1

You use == (comparison) instead of = (assignment) here:

int Test::Randomize()
{
    Number == 1; // oops!
    std::cout << Number;
    return Number;
}

The comparison here does nothing, so a trash value is used when printing.

于 2013-05-21T02:04:09.560 回答
1

You are not doing anything with your number, the compiler even warned you. Also, the debugger is your friend.

于 2013-05-21T02:05:56.610 回答