简体   繁体   中英

Problems in accessing variables in nested classes

I am trying to access the variable i declare in my nested class, but i fail to get the answer i want at the console. The result i want is 100, but all that i get is a long number. I cannot seem to find the error. This is what i wrote:

#include <iostream>

using namespace std;

class shpia {
public:
    int tot;

    class dhoma1 {
    public:
        int gjatesi;

        int di() {
            return gjatesi * gjatesi;
        }
    };

    dhoma1 dh1;

    void redi(){
        cout<<dh1.di();
    }
};

int main()
{
    shpia::dhoma1 k;
    k.gjatesi = 10;
    shpia r;
    r.redi();

    return 0;
}

There's nothing surprising about your result. You seem to think

shpia::dhoma1 k;
k.gjatesi=10;

will define a dhoma1 for all shpia objects you will create. This is wrong. You just defined a shpia::dhoma1 object that has nothing to do with shpia objects.

When you then define

shpia r;

this will create in r another dhoma1 , unrelated to the first one, which is not initialized. Hence when you print the square you're getting non-sense.

You are accessing uninitialized memory. Here you create an instance of the nested class, and initialize its member:

shpia::dhoma1 k;
k.gjatesi=10;

And here you create an instance of the main class, which has nothing to do with the k . It already has a nested class member variable defined itself (r.dh1)

shpia r;
r.redi();
return 0;

Because of this new declaration, the nested class of r has no defined value and when you call redi() , you will access undefined memory and therefore get some random number. Depending on the actual runtime layout of your application, this value can change. It is undefined and you have to define it before you use it.

To fix this, you should use the nested class member of the main class instead, like this:

shpia r;
r.dh1.gjatesi = 10;
r.redi();
return 0;

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