android:无法访问struct静态数据成员

时间:2011-09-22 18:08:12

标签: android c++

链接应用程序时我遇到了下一种错误:

undefined reference to 'MyStructure::K_VARIABLE_A
undefined reference to 'MyStructure::K_VARIABLE_B
...

结构在“MyStructure.h”中定义为:

struct MyStructure
{
const static int K_VARIABLE_A=1;
const static int K_VARIABLE_B=2;
...
}

我怎样才能摆脱这个错误?

我的源代码在Windows平台上成功编译,但在编译android平台时我得到了上面提到的错误。

此结构的标头正确包含在.cpp文件中。

提前致谢。

3 个答案:

答案 0 :(得分:1)

在类/结构的范围内定义常量值的首选方法是:

struct MyStructure
{
    enum
    {
        K_VARIABLE_A=1,
        K_VARIABLE_B=2,   // Note that you CAN keep the trailing comma
        ...
    };
};

答案 1 :(得分:1)

您正在使用的构造称为类内初始化。它是整型常量类型的有效语法,但它可能不适用于某些编译器。

解决方案是:

const int MyStructure::K_VARIABLE_A=1;
const int MyStructure::K_VARIABLE_B=2;

在你的一个cpp(Implementation)文件中。

答案 2 :(得分:1)

对于每个静态变量,您需要在编译单元(传统的.cpp文件)中声明它们,以便它们具有这样的存储空间

#include "Mystructure.h"

const int MyStructure::K_VARIABLE_A = 1;
const int MyStructure::K_VARIABLE_B = 2;
// other stuff here...

这是因为静态成员不属于结构/类的任何实例,但需要在某处声明存储空间。编译器将其留给程序员来指定哪个编译单元包含静态成员的存储,但传统上它们将被放在与.h文件对应的.cpp文件中。

相关问题