连接两个不同类型的向量会丢失信息

时间:2013-05-05 14:58:10

标签: c++ vector

我想结合两个向量,但是当我尝试在屏幕上写入结果时,我得到没有int数的结果,这是两个。我想得到结果:一两三四五十 你能帮帮我,怎么解决?谢谢

#include <iostream>
#include <string>
#include <vector>

using namespace std;


template<typename T>
class One
{
protected:
    T word;
    T word2;

public:
    One() {word = "0"; word2 = "0";}
    One(T w, T w2) {word = w; word2 = w2;}
    virtual const void Show() {cout << word << endl; cout << word2 << endl;}
};

template<typename T>
class Two : public One<T>
{
protected:
    int number;
public:
    Two() {number = 0;}
    Two(T w, T w2, int n) : One(w,w2) {number = n;}
    virtual const void Show () {cout << word << endl; cout << word2 << endl; cout << number << endl; }
};


int main ()
{
    vector<One<string>> x;
    vector<Two<string>> x2;

    One<string> css("one","two");
    Two<string> csss("three","four",50);

    x.push_back(css);
    x2.push_back(csss);

    x.insert(x.end(),x2.begin(),x2.end());

    for (int i = 0; i < x.size(); i++)
    {
        x.at(i).Show();
    }

    cin.get();
    cin.get();
    return 0;
}

3 个答案:

答案 0 :(得分:0)

请参阅“切片”的评论。如果你使用指针,你将会遇到这个问题。

#include <iostream>
#include <string>
#include <vector>

using namespace std;


template<typename T>
class One
{
protected:
    T word;
    T word2;

public:
    One() {word = "0"; word2 = "0";}
    One(T w, T w2) {word = w; word2 = w2;}
    virtual const void Show() {cout << word << endl; cout << word2 << endl;}
};

template<typename T>
class Two : public One<T>
{
protected:
    int number;
public:
    Two() {number = 0;}
    Two(T w, T w2, int n) : One(w,w2) {number = n;}
    virtual const void Show () {cout << word << endl; cout << word2 << endl; cout << number << endl; }
};


int main ()
{
    std::vector< One<string> * > x;
    std::vector< Two<string> * > x2;

    One<string> css("one","two");
    Two<string> csss("three","four",50);

    x.push_back(&css);
    x2.push_back(&csss);

    x.insert(x.end(),x2.begin(),x2.end());

    for (size_t i = 0; i < x.size(); i++)
    {
        x.at(i)->Show();
    }

    cin.get();
    cin.get();
    return 0;
}

答案 1 :(得分:0)

您遇到了一个名为切片的问题。

问题是向量x只能存储One<string>类型的对象 当您插入类型为Two<string>的对象时,对象将在复制上切片(因为当您将内容放入向量时,它们将被复制)。所以基本上你将Two<string>类型的对象复制到一个只能容纳One<String>的位置,这样你就会丢失额外的信息(它被切掉)。

 // Example:
 Two<string>    two("plop","plop1",34);
 two.show;

 One<string>    one("stop","stop1");
 one.show;

 one = two;    // copy a two into a one.
 one.show;   // Notice no number this time.

答案 2 :(得分:0)

这不是你期待的多态性

x.at(i).Show();

只需拨打Show的{​​{1}}即可。您没有调用类One的方法Show