C++ 继承不';使用loop时不工作
我的代码中的继承有一个小问题——当我在循环中的另一个“if”语句中添加相同的代码时,它突然停止工作。 下面是我用于“main.cpp”的代码:C++ 继承不';使用loop时不工作,c++,inheritance,C++,Inheritance,我的代码中的继承有一个小问题——当我在循环中的另一个“if”语句中添加相同的代码时,它突然停止工作。 下面是我用于“main.cpp”的代码: #包括“bibl.h” 使用名称空间std; int main() { INTO; Vec2试验; 而(1) { coutgetItem(0)->Show();可以工作,但在另一种情况下不行。 此问题的原因是什么?我如何修复它?项a(“测试”,100);位于堆栈上,并且在块的末尾超出范围。因此,该项无法保留指向它的指针。测试。添加项(&a)一个是该if语
#包括“bibl.h”
使用名称空间std;
int main()
{
INTO;
Vec2试验;
而(1)
{
coutgetItem(0)->Show();可以工作,但在另一种情况下不行。
此问题的原因是什么?我如何修复它?项a(“测试”,100);
位于堆栈上,并且在块的末尾超出范围。因此,该项无法保留指向它的指针。测试。添加项(&a)
一个
是该if语句的本地地址,因此一旦您退出该if语句,地址就指向垃圾。看起来您可以从代码中完全删除指针的使用,您没有任何理由使用它们。您应该在main()中使用开关
函数。开关
允许使用默认
案例,并且更易于阅读。否则,您需要一个ENDelse
语句来处理输入案例,例如o==5
。如果不查看Vec2
的外观,则很难提出解决方案。
#include "bibl.h"
using namespace std;
int main()
{
int o;
Vec2 test;
while(1)
{
cout<<"1. Add item and show."<<endl<<"2. Show."<<endl;
cin>>o;
if(o==1)
{
InhItem a("Test",100);
test.addItem(&a);
cout<<"This show works:"<<endl;
test.getVec1(0)->getItem(0)->Show();//This code works.
}
else if(o==2)
{
cout<<"This show doesn't work:"<<endl;
test.getVec1(0)->getItem(0)->Show();//This doesn't.
}
}
system("pause");
return 0;
}
#ifndef TEST1
#define TEST1
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Item
{
protected:
string im;
string theme;
public:
Item(string im=" ", string theme=" "):im(im),theme(theme)
{
}
~Item()
{
}
string getTheme()
{
return theme;
}
virtual void Show()
{
}
};
class InhItem:public Item
{
int tst;
public:
InhItem(string im=" ", int tst=0):Item(im),tst(tst)
{
}
~InhItem()
{
}
void Show()
{
cout<<tst<<endl;
}
};
class Vec1
{
vector<Item*> Vec1a;
string theme;
public:
Vec1(string theme=" "):theme(theme)
{
}
~Vec1()
{
}
void addToVec1a(Item *item)
{
Vec1a.push_back(item);
}
string getTheme()
{
return theme;
}
Item *getItem(int p)
{
return Vec1a[p];
}
};
class Vec2
{
vector<Vec1*> Vec2a;
public:
Vec2()
{
}
~Vec2()
{
}
void addToVec2(Vec1 *vec1)
{
Vec2a.push_back(vec1);
}
void addItem(Item *item)
{
for(int i=0;i<=Vec2a.size();i++)
{
if(i==Vec2a.size())
{
addToVec2(new Vec1(item->getTheme()));
Vec2a[i]->addToVec1a(item);
break;
}
else if(Vec2a[i]->getTheme().compare(item->getTheme())==0)
{
Vec2a[i]->addToVec1a(item);
break;
}
}
}
Vec1 *getVec1(int r)
{
return Vec2a[r];
}
};
#endif