2013-05-05 62 views
0

我想連接兩個向量,但是當我嘗試在屏幕上寫入結果時,我得到的結果沒有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; 
} 
+0

閱讀[object slicing](http://en.wikipedia.org/wiki/Object_slicing)。 – 2013-05-05 15:03:43

+0

閱讀本文:[C++中的切片問題是什麼?](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c) – jrok 2013-05-05 15:04:04

回答

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; 
} 
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. 
0

這不是多態性這是你

x.at(i).Show(); 

只要你打電話的OneShow期待。您沒有調用Two類的Show

相關問題