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

3 回答 3

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;
}
于 2013-05-05T15:06:20.550 回答
0

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

问题是 vectorx只能存储 type 的对象One<string>
当您插入类型Two<string>的对象时,该对象在复制时被切片(因为当您将事物放入向量中时,它们会被复制)。所以基本上你将一个类型的对象复制Two<string>到一个只能保存 a 的位置,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.
于 2013-05-05T15:07:50.530 回答
0

这不是您所期望的多态性

x.at(i).Show();

只是你打电话ShowOne. 你没有调用Showclass的方法Two

于 2013-05-05T15:09:16.093 回答