使用公共成员函数访问私有成员变量时出错:变量"未在此范围内声明"

时间:2016-02-10 04:53:52

标签: c++ class oop static private

任何无法返回多维数组的人的更新

进一步阅读:Returning multidimensional array from function

我在标题中声明了static int变量。我已经在.cpp文件(实施文件?)中对其进行了定义,如下面的相关代码所示......

Card.h

#ifndef CARD_H
#define CARD_H

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

#endif /* CARD_H */

Card.cpp

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的价值?

2 个答案:

答案 0 :(得分:2)

您忘记了Card::

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

您不应该在方法定义中使用static。另外,当您应该返回int[][]时,您会尝试返回int

将您的班级更改为:

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

答案 1 :(得分:1)

首先,方法名称为Card::palette,而不仅仅是paletteCard::palette是你应该在方法定义中使用的。

其次,静态方法定义不应包含关键字static

第三,您期望如何能够将数组作为int值返回???鉴于您的_palette数组的声明,要从函数返回它,您必须使用int (*)[3]返回类型或int (&)[][3]返回类型

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

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

typedef可以使它更具可读性。