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

kjthegm6  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(139)

我正在编写一个类对象的向量,每个类对象都包含一个C++中的Template变量,以便它允许我处理不同类型的数据。
我使用以下代码:

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

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

yacmzcpb

yacmzcpb1#

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

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();
}
*/

相关问题