繁体   English   中英

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

[英]concatenating two vectors of different types loses information

我想合并两个向量,但是当我尝试在屏幕上写入结果时,我得到的结果没有整数,即int。 我想得到结果:一二三四50您能帮助我,如何解决? 谢谢

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

请参阅注释“切片”。 如果使用指针,则可以解决此问题。

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

您正在遭受称为切片的问题。

问题是向量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.

不是您期望的多态

x.at(i).Show();

您只是简单地打电话给Show of One 您没有调用类Two Show方法,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM