【发布时间】:2015-10-20 07:13:14
【问题描述】:
所以我发现了一些与在类中定义私有变量有关的事情。
目前,我的 Apple.h 文件如下所示:
#ifndef Apples_h
#define Apples_h
class Apples {
public:
Apples();
void eat();
void peel();
void slice();
private:
int _seeds;
String _type; // originally int by mistake
};
#endif
我的 Apple.cpp 文件如下所示:
#include "Apples.h"
int _seeds = 0; // default
String _type = 0; // default
Apples::Apples(){
_seeds = 5000;
_type = "notYummy";
}
// pretend all the public methods are implemented and are fine (no issues with them)
这实际上工作正常:我在我的头文件和 .cpp 文件中定义了一个私有属性 _seeds。
当我在其他地方定义属性 _seeds 时出现问题,比如在父类/主文件中。
然后它抱怨它有多个定义。对我来说,这有点奇怪,因为我认为 Apple.cpp 中的 _seeds 属性应该是私有的(因此是未知的),但它以某种方式将其拾取并在另一个文件中发生冲突。
我找了一个制作类的例子,他们没有在 .cpp 文件中定义类属性,而只是在头文件中定义了它,它似乎神奇地在 .cpp 中创建了这些私有属性文件(它们没有在 .cpp 文件的任何地方定义)。
我的“最接近”的语言可能是 Java,我在类实现文件中定义了所有类变量/属性,所以我有点困惑。
谁能确认一下:
c/c++ 不是这种情况,您应该只在头文件中定义私有属性。
类 .cpp 文件中的任何变量/属性都是“全局命名空间”中的某种方式,它们可能会在其他文件中发生冲突。
如果第二点为真,是否可以通过在另一个类/文件中调用 _seeds 来实际访问它们?
(可能没关系,因为我认为这只是语言问题,但这是 arduino 的代码。)
【问题讨论】:
-
这听起来不可能。类中的属性仅限于类。你能发布你的代码吗?
-
TL;DR:
_type应该是int还是string? -
请不要在变量名前加上下划线 -
Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace -
嗯,是的,哎呀。 int 应该是一个字符串。但这不是问题所在。 >.> 嗯,我以为私有属性使用下划线是一种惯例?你是说带下划线的名字总是在全局命名空间中?
-
@Constantin 它们只保留在全局命名空间中。