我正在写一个类对象的向量,每个类对象在 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++ 中访问嵌套类中的变量的正确方法是什么?
可能是因为你没有在父类中定义一些虚函数,像这样?
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();
}
*/