可以在另一个类的方法中使用一个类的成员变量吗?

时间:2017-01-13 00:20:06

标签: c++ class

一个简单的假设示例

A.H

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;
}

2 个答案:

答案 0 :(得分:1)

在班级m_variable

static必须A才能通过班级限定符访问:A::m_variable

非静态成员只能通过类的特定实例(即类类型的特定对象)访问。

如果你必须这样做,你可以:

A a;
int x = a.m_variable;

顺便说一句,由于封装不良,应该避免暴露类的成员变量(使其公开)。

答案 1 :(得分:1)

仅限 声明 的对象 。通常,在实际拥有该类的 实例 之前,您无法访问类中的数据。所以:

"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)

在代码中看起来像:

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

您收到的错误消息引用了您可以在“常规”案例之外执行的操作 声明 成员可以静态。这意味着它是由类的 所有实例 和定义本身共享的成员。

注意:声明(通常在.h文件中)本身不足以使用该成员。您还需要 定义 它(通常在.cpp文件中以及方法定义)。

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