简体   繁体   中英

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. 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). Repeated calls to IncrementNum() do not change anything, num doesn't change.

So I decided to instead change num++ to num = 1 , thinking surely this would force num to be set. 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.

Any idea what could be causing this?

Other info:

I'm using Windows 7 Home Edition and 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. Try to display num with printf() or cout and try the test again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM