【发布时间】:2011-03-03 18:36:19
【问题描述】:
我正在尝试创建一个模板类,当我定义一个非成员模板函数时,我收到“No matching function for call to randvec()”错误。
我有一个模板类定义为:
template <class T>
class Vector {
T x, y, z;
public:
//constructors
Vector();
Vector(const T& x, const T& y, const T& z);
Vector(const Vector& u);
//accessors
T getx() const;
T gety() const;
T getz() const;
//mutators
void setx(const T& x);
void sety(const T& y);
void setz(const T& z);
//operations
void operator-();
Vector plus(const Vector& v);
Vector minus(const Vector& v);
Vector cross(const Vector& v);
T dot(const Vector& v);
void times(const T& s);
T length() const;
//Vector<T>& randvec();
//operators
Vector& operator=(const Vector& rhs);
friend std::ostream& operator<< <T>(std::ostream&, const Vector<T>&);
};
我在上面所有这些函数之后定义的有问题的函数是:
//random Vector
template <class T>
Vector<double>& randvec()
{
const int min=-10, max=10;
Vector<double>* r = new Vector<double>;
int randx, randy, randz, temp;
const int bucket_size = RAND_MAX/(max-min +1);
temp = rand(); //voodoo hackery
do randx = (rand()/bucket_size)+min;
while (randx < min || randx > max);
r->setx(randx);
do randy = (rand()/bucket_size)+min;
while (randy < min || randy > max);
r->sety(randy);
do randz = (rand()/bucket_size)+min;
while (randz < min || randz > max);
r->setz(randz);
return *r;
}
然而,每次我在我的主函数中使用如下行调用它:
Vector<double> a(randvec());
我得到了那个错误。但是,如果我删除模板并使用“double”而不是“T”来定义它,那么对 randvec() 的调用就可以完美地工作。为什么不识别 randvec()?
附:不要介意标记为 voodoo hackery 的位 - 这只是一个廉价的 hack,这样我就可以绕过另一个 problem I encountered。
【问题讨论】:
标签: c++ class templates function random