好的,所以我遇到了一些非常奇怪的问题,即在类中存储一组基类指针,然后将此基类指针设置为等于一些动态分配的派生类指针。 我的代码太长且因 GUI 调用而臃肿,无法在此处发布,因此我将在此处制作一些模拟代码来演示我正在使用的方法
基类 - 基类
class Base
{
public:
Base(){ // do nothing}
virtual void SetUI(){ // do nothing}
}
派生类 - 派生
class Derived : public Base
{
public:
Derived() : Base() { // do nothing}
virtual void SetUI(){// do nothing}
}
这是一个基本上为我的程序保存数据的类,它包含一个指向基类的指针数组。这些指针通过指向动态创建的派生类类型的对象来初始化。
class HelperClass
{
private:
Base * basearray[2];
public:
HelperClass()
{
basearray[0] = new Derived;
basearray[1] = new Derived;
}
Base * getBaseArray(int key)
{
return this->basearray[key];
}
}
这是我的“主要”,这是一切开始变得奇怪的地方。
int main()
{
HelperClass hold;
hold.getBaseArray(0)->setUI();
// NOTHING HAPPENS ABOVE, THE CODE DOESN'T EVEN REACH THIS POINT, IT JUST GET'S LOST SOMEWHERE IN //THE ABOVE STATEMENT. i KNOW THIS BECAUSE I PUT AN exit(0) inside the function setUI() for both the //base and derived class and the program doesn't exit.
// this also does nothing
if(hold->getBaseArray(0) || !hold->getBaseArray(0))
exit(0);
return 0;
}
但奇怪的是,如果我做类似下面的事情,我只是声明一个基类指针并让它指向派生类的一个动态创建的对象,一切正常。
int main()
{
Base *hold;
hold = new Derived;
hold->setUI(); // <- this works polymorphically
return 0;
}
有谁知道为什么当我尝试使用 HelperClass 中的基类指针数组时我的程序停止工作?当我尝试执行 getBaseArray(int) 时,它不会返回任何内容,这会导致类似
的语句if(hold->getBaseArray(0) || !hold->getBaseArray(0)) {exit(0);}
不让程序退出,这很奇怪,因为 getBaseArray() 返回的指针要么为 null 要么为非 null,这意味着程序无论如何都应该退出
最佳答案
我(和我的编译器)发现你在第一个 main()
- 您在基类和派生类中声明了
SetUI()
,但在main
中您尝试调用setUI()
。也许您的项目中同时具有这两种功能,这就是您什么也没收到的原因。 - 您将
hold
声明为对象而不是指针。有了这个你就不能像hold->someFn()
那样做。你应该像hold.someFn()
那样调用它们。
这是经过更正的代码。它由我运行没有问题。试试吧。
struct Base
{
Base(){}
virtual ~Base() {}
virtual void SetUI() {
cout << "base" << endl;
}
};
struct Derived : public Base
{
Derived() : Base() {}
virtual ~Derived() {}
virtual void SetUI() {
cout << "derived" << endl;
}
};
class HelperClass
{
Base * basearray[2];
public:
HelperClass() {
basearray[0] = new Derived;
basearray[1] = new Derived;
}
~HelperClass() {
delete basearray[0];
delete basearray[1];
}
Base *getBaseArray(int key) {
return basearray[key];
}
};
int main()
{
HelperClass hold;
hold.getBaseArray(0)->SetUI();
if(hold.getBaseArray(0))
cout << "some output" << endl;
return 0;
}
关于c++ - 涉及指针成员变量和多态性的很奇葩的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20200500/