使用public成员函数访问私有成员变量时出错:变量"was not declared in this scope"
Error when using public member function to access private member variable: Variable "was not declared in this scope"
为遇到返回多维数组问题的任何人更新
进一步阅读:Returning multidimensional array from function
我在 header 中声明了一个 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
的值吗?
你忘记了 Card::
int (*Card::palette())[3]{
return _palette;
}
你不应该在方法定义中有 static
。此外,当您应该 return int
.
时,您正在尝试 return int[][]
将您的 class 更改为:
class Card {
private:
static int _palette[][3];
public:
static int (*palette())[3];
};
首先,方法名称是Card::palette
,而不仅仅是palette
。 Card::palette
是您应该在方法定义中使用的内容。
其次,静态方法定义不应该包含关键字static
.
第三,您如何期望能够 return 数组作为 int
值???给定你的 _palette
数组的声明,从一个函数到 return 它你必须使用 int (*)[3]
return 类型或 int (&)[][3]
return类型
int (*Card::palette())[3] {
return _palette;
}
或
int (&Card::palette())[][3] {
return _palette;
}
并且 typedef 可以使其更具可读性。
为遇到返回多维数组问题的任何人更新
进一步阅读:Returning multidimensional array from function
我在 header 中声明了一个 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
的值吗?
你忘记了 Card::
int (*Card::palette())[3]{
return _palette;
}
你不应该在方法定义中有 static
。此外,当您应该 return int
.
int[][]
将您的 class 更改为:
class Card {
private:
static int _palette[][3];
public:
static int (*palette())[3];
};
首先,方法名称是Card::palette
,而不仅仅是palette
。 Card::palette
是您应该在方法定义中使用的内容。
其次,静态方法定义不应该包含关键字static
.
第三,您如何期望能够 return 数组作为 int
值???给定你的 _palette
数组的声明,从一个函数到 return 它你必须使用 int (*)[3]
return 类型或 int (&)[][3]
return类型
int (*Card::palette())[3] {
return _palette;
}
或
int (&Card::palette())[][3] {
return _palette;
}
并且 typedef 可以使其更具可读性。