item[i]=static_cast<T>(the_list[i])
。这一行给我一个错误陈述
[错误]无效使用非静态数据成员'SimpleVector :: item'。
我认为问题出在于类型转换。现在我该怎么办?
template <class T>
class SimpleVector {
public:
SimpleVector();
SimpleVector(int);
SimpleVector(const SimpleVector & copy);
~SimpleVector();
friend istream &operator>>( istream &in, SimpleVector<T> &the_list)
{
for(int i=0;i<the_list.size();i++)
{
in>>the_list[i];
cout<<the_list[i];
item[i]=static_cast<T>(the_list[i]);
}
return in;
}
int size();
T getElementAt(int n);
T & operator[](int index);
private:
T* item;
int length;
};
template<typename T>
void doWork(int dataSize)
{
SimpleVector<T> list(dataSize);
std::cout << "Please enter the data:" << std::endl;
cin>>list;
int index;
SimpleVector<T> s;
cout<<"Enter the index whose values you need to retrieve\n";
cin>>index;
cout<<s.getElementAt(index);
}
int main()
{
int i,choice;
cout<<"Enter the size of the array\n";
cin>>i;
cout<<"Type of data you need to enter\n";
cout<<"Press 1 for int\n";
cout<<"Press 2 for double\n";
cout<<"Press 3 for string\n";
cin>>choice;
switch(choice)
{
case 1:
doWork<int>(i);
break;
case 2:
doWork<double>(i);
break;
case 3:
doWork<string>(i);
break;
}
return 0;
}
答案 0 :(得分:0)
您的代码看起来有点复杂,但我的猜测是不需要使用重载的&gt;&gt;。而只是在doWork()函数中创建泛型数组,并将该数组传递给类中新创建的函数。现在您可以将数组分配给&#39; * item&#39;因为两者都是通用类型。