C++ 一个类的成员变量可以在另一个类的方法中使用吗?
一个简单的假设例子 A.h B.cppC++ 一个类的成员变量可以在另一个类的方法中使用吗?,c++,class,C++,Class,一个简单的假设例子 A.h B.cpp #包括 使用名称空间std; void B::方法() { int x=(A::m_variable)*2;//为什么会出现一个错误,指出“此行非静态数据成员的使用无效”。 coutm_变量必须是类A中的静态,才能通过类限定符访问:A::m_变量 非静态成员只能通过类的特定实例(即类类型的特定对象)访问 如果必须这样做,您可以: A a; int x = a.m_variable; 顺便说一句,由于封装不好,应该避免公开类的成员变量(使其公开)。仅类声明
#包括
使用名称空间std;
void B::方法()
{
int x=(A::m_variable)*2;//为什么会出现一个错误,指出“此行非静态数据成员的使用无效”。
coutm_变量
必须是类A中的静态
,才能通过类限定符访问:A::m_变量
非静态成员只能通过类的特定实例(即类类型的特定对象)访问
如果必须这样做,您可以:
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)
您收到的错误消息引用了您可以在“常规”情况之外执行的操作。可以将成员声明为静态。这意味着它是由类的所有实例和定义本身共享的成员
注意:声明(通常在.h
文件中)本身不足以使用成员。您还需要定义它(通常在.cpp
文件中以及方法定义中)
将代码缩进4个空格(或高亮显示并按ctrl+k),确保代码前后都有空行。“我无法使用降价来正确显示以下代码”谷歌搜索“stackoverflow降价代码”时的第一个点击是。我想说的不是太多。你为什么要这样做?
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
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