使用公共成员函数访问私有成员变量时出错:变量"was not declared in this scope"
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 */
卡.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;
}
但是当我编译时,我收到此错误:
..sourcesrcCard.cpp: In function 'int palette()':
..sourcesrcCard.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 可以使其更具可读性。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查