我目前正在尝试编写一个包含虚拟方法和朋友的模板类。 我想在我的测试功能中调用它们。我的代码是:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <iterator>
#include <array>
using namespace std;
template <class T> class ProcessorBase;
template <class T> ostream& operator<<(ostream &, const ProcessorBase<T> &);
template<class T>
class ProcessorBase
{
protected:
vector<T> v;
public:
ProcessorBase<T>& newElement(const T & t)
{
v.push_back(t);
return *this;
}
virtual T process()=0;
friend ostream& operator<< <>(ostream & output, const ProcessorBase<T> & o);
};
template<class T>
ostream& operator<<(ostream & output, const ProcessorBase<T> & o)
{
for (std::vector<T>::iterator it = o.v.end() ; it != o.v.begin() && it >10+o.v.begin(); --it)
output<<*it<<endl;
return output;
}
template<class T>
class ProcessorSummer: public ProcessorBase<T>
{
public:
T process()
{
T sum=0;
for (std::vector<T>::iterator it = ProcessorBase<T>::v.begin() ; it != ProcessorBase<T>::v.end(); ++it)
sum=sum+ *it;
return sum;
}
};
template <class T>
void test(T n = 200)
{
ProcessorSummer<T> ps;
for(T k=0;k<n ;++k)
{
T t= (k / static_cast<T>(2));
ps.newElement(t);
}
cout<<ps.process()<<endl;
cout<<ps.v<<endl;
}
int main()
{
test<int>();
test<double>();
test<float>(3);
system("PAUSE");
return 0;
}
编译失败:
error C2248: 'ProcessorBase<T>::v' : cannot access protected member declared in class 'ProcessorBase<T>'
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::vector<_Ty>' (or there is no acceptable conversion)
你能帮我查一下确切的问题吗?
答案 0 :(得分:1)
arr
包含指针,因此您无法使用.
,需要->
。