[英]Can an member variable of one class be used in a method of another class?
A simple hypothetical example一个简单的假设例子
using namespace std;
class A {
public:
int m_variable=5;
};
#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
m_variable
在类A
必须是static
A
,才能通过类限定符访问: 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 .
可以将成员声明为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.注意:声明(通常在
.h
文件中)本身不足以使用该成员。 You also need to define it (typically in a .cpp
file along with method definitions).您还需要定义它(通常在
.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.