如何从 C++ 中的继承类模板中提取数据

问题描述 投票:0回答:1

我正在写一个类对象的向量,每个类对象在 C++ 中都有一个模板变量,这样我就可以处理不同类型的数据。

我正在使用以下代码:

#include <iostream>
#include <memory>
//Declare Vector library to work with vector objects.
#include <vector>
#include <string>
    
using namespace std;

class AItem{
};
    
template <class OBJ>
    
//Object that will hold template data.
class Item : public AItem {
    public:
        //Variable to store the values. TODO: Verify if this can be made into a TEMPLATE to accept any value.
        OBJ value;
    
        //Constructor to store values.
        Item(OBJ _value): value(_value){}

        ~Item(){ 
            cout << "Deleting " << value << "\n";
        }
};

//Main Thread.
int main(){
    //##################################################
    //##################################################
    //                TEST SECTION

    //Create new Items.
    Item<string> *itObj = new Item<string>("TEST");
   //Create a Vector that stores objects.
    vector <shared_ptr<AItem>> v1;

    //Store each item in the Array.
    v1.push_back(shared_ptr<AItem>(itObj));

    //cout<<&v1.getValue()<<"\n";

    //Iterate through each one and retrieve the value to be printed.
    //TODO: FIX THIS
    for(auto & item: v1){
        cout<<item<<'\n';
    }
    //##################################################
    //##################################################
    cout<<"Cpp Self Organizing Search Algorithm complete.\n";
    return 0;
}

我想检索插入的值,但是每当我迭代是使用指针还是访问数据时,我只得到一个内存地址,或者我被告知类 AItem 没有属性 value。在 C++ 中访问嵌套类中的变量的正确方法是什么?

c++ class variables vector nested
1个回答
0
投票

可能是因为你没有在父类中定义一些虚函数,像这样?

struct AItem {
  virtual void a() { printf("AItem::a()\n"); }
  virtual void b() { printf("AItem::b()\n"); }
};
template <class OBJ> struct Item : public AItem {
public:
  OBJ value;
  Item(OBJ _value) : value(_value) {}
  void a() override { printf("Item::a()\n"); }
  void b() override { printf("Item::b()\n"); }
  ~Item() { std::cout << "Deleting " << value << "\n"; }
};
/* Use it like below
for (auto &item : v1) {
  item->a();
  item->b();
}
*/
© www.soinside.com 2019 - 2024. All rights reserved.