【发布时间】:2013-06-19 16:45:14
【问题描述】:
我正在开发适用于 iOS 和 Android 的应用程序,并且在我的 C++ 代码中得到了非常不同的结果。我遇到的问题是输入一个函数会踩到一个成员变量是一个派生类。举个例子
int main()
{
A** arrayOfA = new A[10];
for (int i = 0; i < 10; ++i)
{
arrayOfA[i] = new D();
}
return 0;
};
class A
{
// Original code here. After this is the added function and member variable that breaks it
public:
virtual u32 GetterFunction() = 0;
protected:
u32 ProblemVariable;
};
class B : A
{
public:
B(u32 index) { ProblemVariable = index }
virtual u32 StompedGetter() = 0;
virtual u32 GetterFunction() { return ProblemVariable; }
void Initialize()
{
u32 sometimesBunkNumber = StompedGetter();
}
protected:
u32 StompedVariable;
};
class C : A
{
public:
virtual u32 GetterFunction() { return 0; }
};
class D : B
{
B() { Initialize(); }
virtual StompedGetter() { return StompedVariable; }
}
class E : B
{
virtual StompedGetter() { return 0; }
}
那么,这里的问题是一切正常,直到我将成员变量和虚拟 getter 放入类 A 中。当调用 getter 时,它会随机给出一个双层编号。它可能会工作 2 次,然后它会返回一个错误的数字(显然是从内存中的错误位置抓取)。该功能是否为虚拟并不重要,但它是理想的解决方案。最糟糕的是,它在 iOS 版本上编译并运行良好,但在 Android 上它就死了。就像澄清一样,它一直运行到它在 A 类的数组中初始化 B 类。抱歉,如果这非常含糊,但感谢所有帮助。提前致谢!
【问题讨论】:
-
您能否在其中添加一个
main来说明问题或至少说明您是如何调用这些方法的 -
您是否正确构建了所有依赖对象文件? IE。你能打破单一定义规则吗?您能否用实际代码进一步解释 “作为澄清,它会一直运行,直到它在 A 类的数组中初始化 B 类。” 的含义?
-
这是真实的代码吗?为什么不使用构造函数(例如 B())来初始化成员变量“u32 StompedVariable;”到一个已知值?
-
A** arrayOfA = new A[10];那不应该是新的 A* [10]; ?以你的方式,你可能会遇到内存问题,因此为什么有时它会起作用,有时却不起作用。
-
@user2502064:您不会逐字发布专有代码,而是发布您在进行所有调试时使用的精简版testcase。如果您无法提供其中之一,那么我们将无法帮助您,更重要的是,您不太可能能够帮助自己。