2013-05-05 43 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

相关问题