0

2 つのベクトルを結合したいのですが、画面に結果を書き込もうとすると、Two にある int 番号のない結果が得られます。結果を取得したい: 1 2 3 4 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();

を呼び出しているだけShowですOneShowclass のメソッドをTwo呼び出していません。

于 2013-05-05T15:09:16.093 に答える