簡體   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