简体   繁体   中英

Accessing a method that has to print a data member using an object pointer of a class

I have got the following code and I got an unexpected result does anybody know why that happened??!!

#include <iostream>

using namespace std;
class A2
{
public:

    void disp ()
    {
        cout<<m<<endl;
    }
private:
    int m = 4;//this is the data member I want to show
};

int main()
{
    A2 al;
    al.disp();// the output of this is 4
    A2 *a2;

    a2->disp(); 
    //here is the unexpected result, I think that it should be 4

    return 0;
}

a2 here is just uninitialized. You must make a2 point to the object and then call the function.

A2* a2 = &al; // points to a1
a2->disp();

Or

A2* a2 = new A2(); // constructs another A2 objcet and points to
a2->disp();
delete a2;

More about pointers, see https://en.cppreference.com/w/cpp/language/pointer

In your line:

A2 *a2;

You have to complete with:

A2 *a2 = new A2();

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