我正在编写一个类对象的向量,每个类对象都包含一个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++中访问嵌套类中的变量的正确方法是什么?
1条答案
按热度按时间yacmzcpb1#
也许是因为你没有在父类中定义一些虚函数,像这样?