使用std :: vector单元格中的Derived实例替换Base实例

时间:2016-05-04 13:19:29

标签: c++ vector replace derived-class base-class

假设我有一个基类Derived和一个派生类std::vector<Base> vec(k)以及一个用k Base个实例初始化的Base。< / p>

在迭代向量时,如何将Derived的实例替换为for (auto i = vec.begin(); i != vec.end();) { if (j == 3) { *i = 9; } else { ++i; } } 的实例?

如果类没有像int这样的层次结构,我可以这样做:

#include<iostream>
#include<vector>
#include<ostream>

class Base
{

public:

    friend std::ostream& operator<<(std::ostream& o, Base& e)
    {
        return o << e.get_repr();
    }

private:

    virtual std::string get_repr()
    {
        return repr;
    }

private:

    std::string repr = "B";
};

class Derived: public Base
{

private:

    std::string get_repr()
    {
        return repr;
    }

private:

    std::string repr = "D";
};






int main()
{

    std::vector<Base> vec(5);

    int j = 0;
    for (auto i = vec.begin(); i != vec.end(); ++j)
    {
        if (j == 3)
    {
        *i = Derived();
    }
    else
    {
        ++i;
    }
    }

    for (auto i = vec.begin(); i != vec.end(); ++i)
    {
        std::cout << *i << ' ';
    }
    std::cout << std::endl;

}

但是对于派生类和基类,这不起作用,如下所示:

B B B B B

输出为:

Base

那么如何将Derived - 实例替换为int main() { std::vector<Base*> vec(5); int j = 0; for (auto i = vec.begin(); i != vec.end(); ++j) { if (j == 3) { *i = new Derived(); } else { *i = new Base(); ++i; } } for (auto i = vec.begin(); i != vec.end(); ++i) { std::cout << **i << ' '; } std::cout << std::endl; } - 实例?

修改

我将单元格内容更改为指针,如评论中所示。我是这样做的:

B B B B B

但我仍然得到sed ...为什么?

0 个答案:

没有答案