[英]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;
};
#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.