質問

Is it possible to access non static data members outside their class? Say you have an example like the following. I know it does not make much sense as an example, but I just want to understand how to access a non static data member. If the following is compiled it generates an error:

 C.h|70|error: invalid use of non-static data member ‘C::age’|

//C.h

class C{
  public:
    int age;
};
 int getAge();

//C.cpp

C::C()
{
    age  = 0;
}
int getAge(){
   return (C::age);
}
役に立ちましたか?

解決

Non-static members are instance dependent. They are initialized when a valid instance is initialized.

The problem with your example is that, it tries to access a non-static member through the class interface without first initializing a concrete instance. This is not valid.

You can either make it static:

class C{
public:
    static int age;
};

which requires you to also define age before using at runtime by: int C::age = 0. Note that value of C::age can be changed at runtime if you use this method.

Or, you can make it const static and directly initialize it like:

class C{
public:
    const static int age = 0;
};

In this case, value of C::age is const.

Both of which will let you get it without an instance: C::age.

他のヒント

Without making it static, you would have to create a value:

Either an lvalue:

C c;

return c.age;

or an rvalue:

return C().age;
// or
return C{}.age;

The problem with your code is that you try to access the age member without creating an instance of the class. Non-static data members of a class are only accessible through an instance of the class, and in your case no instance is created.

The reason why you can't is because local variables are allocated at runtime onto the stack - you can obtain its position if you really wanted to with some inline asm but it would require some debugging to obtain the stack position and the later (after the function) you want to access it the more likely it will have long been overwritten by something else.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top