使用循环时,继承不起作用

时间:2014-05-12 19:35:46

标签: c++ inheritance

我的代码中有一个小继承问题 - 当我在循环中的另一个“if”语句中添加相同的代码时,它会突然停止工作。 这是我用于“ main.cpp ”的代码:

#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;
}

bibl.h ”的代码:

#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

当我在第1次添加项目后尝试使用第2个“if”时,它没有显示 - 在第1个“if” test.getVec1(0) - &gt; getItem(0) - &gt;显示(); 有效,但在另一个实际上没有。 这个问题的原因是什么,我该如何解决?

0 个答案:

没有答案