簡體   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