1

当我编译以下内容时,

#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:错误:无效使用不完整类型“类向量”

vector_test.cpp:7:26: 错误: 'class Vector' 的声明

我究竟做错了什么?

4

2 回答 2

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;
}
于 2012-12-08T00:14:02.367 回答
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;
}

检查:http: //ideone.com/8n9UO1

于 2012-12-08T00:15:36.967 回答