简体   繁体   中英

Can an member variable of one class be used in a method of another class?

A simple hypothetical example

Ah

using namespace std;

class A {
public:
    int m_variable=5;
};

B.cpp

#include <iostream>

using namespace std;

void B::method()
{
    int x=(A::m_variable)*2; //why do get an error stating 'invalid use of non-static data member on this line. 
    cout << x << endl;
}

m_variable must be static in class A to be accessed via class qualifier: A::m_variable

Non-static member can only be accessed via specific instance of the class (ie a specific object of the class type).

If you must do that, you can:

A a;
int x = a.m_variable;

Btw, exposing member variable of a class (making it public) should be avoided due to bad encapsulation.

A class only declares what objects would look like . In general you cannot access data in a class until you actually have instances of that class. So:

"class A" //declares (or describes) what objects of the "A type" look like

"object A1" of "class A" //different instances of class A created
"object A2" of "class A" //according to the "definition of A" will
"object A3" of "class A" //have accessible members (if scope permits)

In code that would look like:

class A
{
  public
    int member;
};

//Different instances of A have their own versions of A.member
//which can be accessed independently
A A1;
A A2;
A A3;
A1.member = 2;
A2.member = 3;
A3.member = A1.member + A2.member;
//Now A3.member == 5

The error message you're getting makes reference to something you can do outside of the "general" case . It is possible to declare a member as static . Meaning it's a member shared by all instances of the class and the definition itself.

NOTE : The declaration (typically in a .h file) by itself is insufficient to use the member. You also need to define it (typically in a .cpp file along with method definitions).

class A
{
  public
    int member;
    static int static_member;
};
int A::static_member; //Defines the static member (a bit like making 
                      //an instance of it; but one that's shared).

A A1;
A A2;
A1.static_member = 2; //Now A::static_member == 2
                      //Also A2.static_member == 2
A::static_member = 3; //And now A1.static_member == 3
                      //And also A2.static_member == 3

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