2012-10-15 6 views
1

개인 템플릿 변수로 부스트 행렬을 갖는 클래스 템플릿이 있습니다. 행렬 데이터 유형은 생성 될 때 클래스 유형에 의해 결정됩니다. 이 클래스에는 멤버 매트릭스에 상수를 추가하는 멤버 함수가 있습니다. 상수는 행렬 데이터 유형과 일치합니다. 임의의 상수 값에 대해 업데이트 된 멤버 행렬을 반환하는 오버로드 된 연산자를 작성하는 데 문제가 있습니다. 현재 다른 멤버 함수가이 작업을 수행합니다. 내 코드는 다음과 같습니다. boost :: numeric :: ublas :: matrix가 포함 된 클래스에 대한 연산자 오버로드

/*content from main.cpp compiled with `g++ -o main main.cpp` */ 
#include <iostream> 
#include <boost/numeric/ublas/matrix.hpp> 
#include <boost/numeric/ublas/io.hpp> 

using namespace boost::numeric::ublas; 
using namespace std; 

template <typename T> 
class MTool 
{ 
private: 
matrix<T> m_ME; 

public: 
MTool(int N, int M) { m_ME.resize(M, N); } // constructor 
~MTool() { m_ME.clear(); } // destructor 
void PutMatValues(); // insert values into member matrix 
void AddConst(const T &k) { m_ME+=k; } // add a constant to member matrix 
void PrintMat() { cout << "The ME " << endl << m_ME << endl; } // print the member matrix 

// overloaded operator function 
matrix<T> operator+ <> (const T& kvalue) { return (m_ME+kvalue); } 
}; 

template<typename T> 
void MTool<T>::PutMatValues() 
{ 
    for (unsigned row=0; row<m_ME.size1(); row++) 
     for (unsigned col=0; col<m_ME.size2(); col++) 
      m_ME(row,col)=static_cast<T> (row*col); 
} 

int main() 
{ 
    MTool<double> mymat(5, 3); 
    double dk=123.67001; 

    mymat.PutMatValues(); 
    mymat.PrintMat(); 
    mymat.AddConst(dk); 
    mymat.PrintMat(); 

    return 0; 
} 

내가받을 컴파일러 오류 중 일부를

error: template-id ‘operator+<>’ in declaration of primary template

error: no match for ‘operator+=’ in ‘((MTool*)this)->MTool::m_ME += k’

나는 C++ 템플릿과 클래스에 오히려 새로운 오전 내 접근 방식에서 누락 된 근본적인 뭔가가 확신합니다. 어떤 제안이라도 대단히 감사하겠습니다. 거의 항상 비회원으로 구현 것 :

답변

0

첫 번째는,이 멤버 연산자 +

MTool<T> operator+ (const T& kvalue) const { ... 

이 멤버 함수와 같은 이진 플러스 운영자 볼 다소 특이한 비록

으로 작성하는 것과 구문 오류입니다 따라서 표현 c + MM + c을 작성할 수 있습니다.

두 번째 오류는 단순히 boost::numeric::ublas::matrix에 스칼라 인수를 사용하는 operator+=이 없음을 지적하고 있습니다. 행렬과 스칼라를 더할 수있는 operator+도 없으므로 operator +에있는 표현 m_ME+kvalue도 컴파일되지 않습니다.

덧셈은 같은 모양의 행렬들 사이에서만 정의됩니다. 행렬의 모든 요소에 스칼라를 추가하는 경우 다음과 같이 작성해야합니다.

void AddConst(const T &k) { 
    for(auto& element : m_ME.data()) 
      element += k; 
} 
관련 문제