繁体   English   中英

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

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

一个简单的假设例子

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在类A必须是static A ,才能通过类限定符访问: A::m_variable

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

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

A a;
int x = a.m_variable;

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

一个类只声明对象的样子 通常,在您真正拥有该类的实例之前,您无法访问该类中的数据。 所以:

"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

您收到的错误消息引用了您可以在“一般”情况之外执行的操作 可以将成员声明static 这意味着它是类的所有实例和定义本身共享的成员。

注意:声明(通常在.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM