简体   繁体   English

为什么不能给这个int赋值?

[英]Why can't I assign this int a value?

I have a class: 我有一堂课:

    class A
    {
    public:
        A();
        ~A();

        void IncrementNum();

    private:
        int num;
    };

    A::A() : num(0)
    {

    }

    A::~A()
    {
    }

    void A::IncrementNum()
    {
        num++;
    }

    int main()
    {
        A obj;
        obj.IncrementNum();
    }

When I set a breakpoint in the constructor, it shows that num is equal to some random value (such as -2483290483), which I take as meaning it's unassigned. 当我在构造函数中设置断点时,它表明num等于某个随机值(例如-2483290483),我认为这是未分配的。 And sure enough, when I call IncerementNum(), and set a breakpoint on the line after num++ , it shows the exact same thing (num equals some random number). 可以肯定的是,当我调用IncerementNum()并在num++之后的行上设置断点时,它显示的是完全相同的东西(num等于某个随机数)。 Repeated calls to IncrementNum() do not change anything, num doesn't change. 重复调用IncrementNum()不会更改任何内容,num不会更改。

So I decided to instead change num++ to num = 1 , thinking surely this would force num to be set. 因此,我决定改为将num++更改为num = 1 ,肯定会强制设置num Nope. 不。 num still shows as being some random number even after discretely setting it to 1. Again, successive calls to the new version of IncrementNum() fail to change its value. 即使将num离散地设置为num仍然显示为某个随机数。再次,对新版本的IncrementNum()的连续调用无法更改其值。

Any idea what could be causing this? 知道是什么原因造成的吗?

Other info: 其他资讯:

I'm using Windows 7 Home Edition and Visual Studio 2010 我正在使用Windows 7家庭版和Visual Studio 2010

You're probably compiling it in Release mode. 您可能正在发布模式下进行编译。 The Compiler sees that num is not being used anywhere and optimized it out. 编译器发现num未被任何地方使用,并对其进行了优化。 Try to display num with printf() or cout and try the test again. 尝试使用printf()cout显示num ,然后重试测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我不能直接将int分配给这样的int指针:int * p = 6 ;? - Why can't I directly assign an int to an int pointer like this: int *p = 6;? 为什么不能为基类的成员分配值? - Why can't I assign a value to a member of the base class? 为什么不能为命名空间中的变量分配值? - Why can't I assign a value to a variable in a namespace? 为什么我不能将 lambdas 作为默认值分配给函数参数? - Why can't I assign lambdas to function parameters as a default value? 为什么我不能在循环中为顺序列表结构赋值 - Why can't I assign a value to a sequential list structure in a loop 为什么我们不能给指针赋值 - Why we can't assign value to pointer 为什么当它是 int 时我不能分配 function 返回右值引用,但当它是 class 时我可以? - Why I can't assign function returning rvalue reference when it's a int but I can when it's a class? 为什么我可以将返回const T&的函数的返回值分配给T变量,而不分配给T变量? - Why can I assign the return value of a function that returns `const T&`, to a `T` variable but not to a `T&` variable? 为什么我可以在没有编译器错误的情况下将Int分配给String? - Why can I assign an Int to a String without compiler error? 为什么我可以在C中分配/比较int和char - Why can I assign/compare int and char in C
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM