编译以下内容时,
#include <boost/numeric/ublas/vector.hpp>
#include <iomanip>
#include <stdio.h>
namespace ublas = boost::numeric::ublas;
template <class T> class Vector
{
private:
ublas::vector<T> m_ublas_vec;
unsigned m_size;
public:
Vector(unsigned s){
m_size = s;
m_ublas_vec.resize(m_size);
}
T &operator () (unsigned idx) {
if(idx >= m_size){
perror("ERROR: Index out of bounds!\n");
exit(1);
}
return m_ublas_vec(idx);
}
// Right-multiply by scalar.
template <class TT, class S>
friend Vector<TT> operator * (const Vector<TT> &, S);
// Left multiply by scalar.
template <class TT, class S>
friend Vector<TT> operator * (S, const Vector<TT> &);
};
template <class T, class S>
Vector<T> Vector<T>::operator * (const Vector<T> &v_in, S scalar){
Vector<T> v_out (v_in.m_size);
v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
return v_out;
}
template <class T, class S>
Vector<T> Vector<T>::operator * (S scalar, const Vector<T> &v_in){
Vector<T> v_out (v_in.m_size);
v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
return v_out;
}
我收到此错误:
vector_test.cpp:49:95:错误:无效使用不完整类型'class Vector'
vector_test.cpp:7:26:错误:'class Vector'的声明
我做错了什么?
答案 0 :(得分:4)
您friend
个函数不声明成员函数。所以,你想把它们定义为
template <class T, class S>
Vector<T> operator * (const Vector<T> &v_in, S scalar){
Vector<T> v_out (v_in.m_size);
v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
return v_out;
}
template <class T, class S>
Vector<T> operator * (S scalar, const Vector<T> &v_in){
Vector<T> v_out (v_in.m_size);
v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
return v_out;
}
答案 1 :(得分:1)
friend
函数不是类的一部分。您不应该通过Vector<T>::
说明符来定义它。正确的是:
template <class T, class S>
Vector<T> operator * (const Vector<T> &v_in, S scalar){
Vector<T> v_out (v_in.m_size);
v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
return v_out;
}
template <class T, class S>
Vector<T> operator * (S scalar, const Vector<T> &v_in){
Vector<T> v_out (v_in.m_size);
v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
return v_out;
}