簡體   English   中英

使用公共成員函數訪問私有成員變量時出錯:變量“未在此范圍內聲明”

[英]Error when using public member function to access private member variable: Variable “was not declared in this scope”

更新給任何難於返回多維數組的人

進一步閱讀: 從函數返回多維數組

我在標頭中聲明了一個static int變量。 我已經在.cpp文件(實現文件?)中定義了它,如下面的相關代碼所示...

卡h

#ifndef CARD_H
#define CARD_H

class Card {
private:
    static int  _palette[][3];
public:
    static int  palette();
};

#endif /* CARD_H */

int Card::_palette[][3]=    {
    {168, 0,   32},
    {228, 92,  16},
    {248, 216, 120},
    {88,  216, 84},
    {0,   120, 248},
    {104, 68,  252},
    {216, 0,   204},
    {248, 120, 248}
};

static int palette(){
    return _palette;
}

但是,當我編譯時,出現以下錯誤:

..\source\src\Card.cpp: In function 'int palette()':
..\source\src\Card.cpp:42:9: error: '_palette' was not declared in this scope
  return _palette;

我的訪問器函數palette()應該能夠獲取私有成員_palette的值?

您忘記了該Card::

int (*Card::palette())[3]{
    return _palette;
}

方法定義中不應包含static 另外,當您應該返回int時,您嘗試返回int[][]

將您的班級更改為此:

class Card {
private:
    static int  _palette[][3];
public:
    static int  (*palette())[3];
};

首先,方法名稱是Card::palette ,而不僅僅是palette Card::palette是您應該在方法定義中使用的。

其次,靜態方法定義不應包含關鍵字static

第三,您如何期望能夠將數組作為int值返回? 給定_palette數組的聲明,要從函數中返回它,您必須使用int (*)[3]返回類型或int (&)[][3]返回類型

int (*Card::palette())[3] {
    return _palette;
}

要么

int (&Card::palette())[][3] {
    return _palette;
}

而typedef可以使其更具可讀性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM