使用文件中的子类对象填充基础对象的向量

时间:2013-10-01 13:34:05

标签: c++ inheritance overloading

我必须使用对象vector<Base<T>*>A填充B。我可以使用以下函数执行此操作:loadAloadB以及operator>>重载。

如何在不必拥有多个loadA()loadB()的情况下进行此操作,而是拥有loadObject()? 那loadObject()怎么样?下面的loadObj()不起作用,我强烈怀疑模板OBJS不是要走的路......

template<typename T>
class Base
{
    public:
        Base() {}
        Base(T tot_) : tot(tot_) {}

        void print() const 
        { std::cout << "Tot : " << tot << std::endl; }

    private:
        T tot;
};

template<typename T>
class A : public Base<T>
{
    public:
        A() : Base<T>(0) {}
        A(T a1, T a2) : Base<T>(a1+a2) {}
};


template<typename T>
class B : public Base<T>
{
    public:
        B() : Base<T>(1) {}
        B(T b1, T b2, T b3) : Base<T>(b1+b2+b3){}
};

template <typename T>
std::istream & operator>>(std::istream& in, A<T>& a)
{ 
    T a1, a2;
    in >> a1; 
    in >> a2;

    a = A<T>(a1,a2);

    return in;
}

template <typename T>
std::istream & operator>>(std::istream& in, B<T>& b)
{ 
    T b1, b2, b3;
    in >> b1; 
    in >> b2;
    in >> b3;

    b = B<T>(b1,b2,b3);

    return in;
}

template <typename T> // from file with 2 columns of type T
bool loadA(const std::string& s, 
                                        std::vector<A<T>>& as)
{
    A<T> a;
    std::ifstream is(s.c_str());
    if (is.good())
    {
        while (!is.eof()) 
        {
            is >> a;
            as.push_back(a);
        }
        is.close();
        return true;
    }
    return false;
}

template <typename T> // from file with 2 columns of type T
bool loadB(const std::string& s, 
                                        std::vector<B<T>>& bs)
{
    B<T> b;
    std::ifstream is(s.c_str());
    if (is.good())
    {
        while (!is.eof()) 
        {
            is >> b;
            bs.push_back(b);
        }
        is.close();
        return true;
    }
    return false;
}

template <typename T, typename OBJS>
bool loadObj(const std::string& s, OBJS o, 
                                        std::vector<Base<T>*>& objs)
{
    OBJS *pO = new OBJS;
    std::ifstream is(s.c_str());
    if (is.good())
    {
        while (!is.eof()) 
        {
            is >> o;
            objs.push_back(pO);
        }
        is.close();
        return true;
    }
    return false;
}

//// IN MAIN
// WHAT IM CURRENTLY DOING
    std::vector<A<T>> as;
    std::string filename = "test";
    loadA(filename, as);

//  for (size_t i=0; i<as.size(); ++i)
//      as[i].print();

    std::vector<Base<T>*> os;

    for (size_t i=0; i<as.size(); ++i)
        os.push_back(&as[i]);

    for (size_t i=0; i<os.size(); ++i)
        os[i]->print();

// WHAT I WOULD LIKE TO DO WITH LOADOBJ

    std::vector<Base<T>*> os2;

    loadObj(filename, A<T>(), os2);

//loadObj(filename2, B<T>(), os2)); ...

    for (size_t i=0; i<os2.size(); ++i)
        os2[i]->print();  // print 0 for all objects instead of the ones in the file "test"

0 个答案:

没有答案