1

LAPACK에 C++ 인터페이스를 작성했지만 일부 메모리 문제로 인해 일부 연산자 오버로딩이 재검토되었습니다.C++의 곱셈 연산자 오버로드

바로 지금, 두 개의 Matrix 객체를 사용하고 적절한 크기로 세 번째를 할당하고 D (GE/SY)를 사용하는 클래스 정의 외부 (* Matrix 클래스의 친구)로 오버로드했습니다. MM을 사용하여 제품을 계산 (새로 할당 된 행렬의 내부 저장소에 저장) 한 다음 해당 새 행렬에 대한 포인터를 반환합니다. I.E.

class Matrix { 
... 
friend Matrix* operator*(const Matrix&, const Matrix&); 
... 
} 

Matrix* operator*(const Matrix& m1, const Matrix& m2) { 
    Matrix *prod = new Matrix(m1.rows_, m2.cols_); 
    if(m1.cols_!=m2.rows_) { 
    throw 3008; 
    } else { 
    double alpha = 1.0; 
    double beta = 0.0; 
    if(m1.symm_=='G' && m2.symm_=='G'){ 
     dgemm_(&m1.trans_,&m2.trans_,&m1.rows_,&m2.cols_,&m1.cols_,&alpha,m1.data_, 
      &m1.rows_,m2.data_,&m1.cols_,&beta,prod->data_,&m2.cols_); 
    } else if(m1.symm_=='S'){ 
     char SIDE = 'L'; 
     char UPLO = 'L'; 
     dsymm_(&SIDE,&UPLO,&m1.rows_,&m2.cols_,&alpha,m1.data_,&m1.rows_,m2.data_, 
      &m2.cols_,&beta,prod->data_,&m2.cols_); 
    } else if(m2.symm_=='S'){ 
     char SIDE = 'R'; 
     char UPLO = 'L'; 
     dsymm_(&SIDE,&UPLO,&m2.rows_,&m1.cols_,&alpha,m2.data_,&m2.rows_,m1.data_, 
      &m1.cols_,&beta,prod->data_,&m1.cols_); 
    }; 
    } 
    return prod; 
}; 

은 그 때 나는

Matrix *A, *B, *C; 
// def of A and B 
C = (*A)*(*B); 

활용이 잘 작동합니다. 문제는 내가 할 때마다 새 행렬을 할당해야한다는 것입니다. 내가 할 수있는 일은 C 행렬을 한 번 할당하고 AB의 제품을 C (C->data_)의 내부 저장소에 저장하는 것입니다. 연산자 오버로딩에서 찾을 수 있었던 것부터,이 작업을 수행하는 좋은 방법을 찾을 수 없습니다. 멤버 함수를 사용하여이 작업을 수행 할 수 있다는 것을 알고 있습니다 (예 : C->mult(A,B)). 가능한 모든 경우에이를 피하고 싶습니다. 비 -CSE 유형을 쉽게 개발할 수 있도록 코딩하고 있습니다. 어떤 아이디어라도 크게 감사 할 것입니다.

+0

'매트릭스'대신 '매트릭스'를 반환합니다. –

+3

완전히 잘못하고 있습니다. 'operator *'는'Matrix'가 아닌'Matrix'를 반환해야합니다. 효율성이 걱정된다면 [이동 할당 연산자] (http://en.cppreference.com/w/cpp/language/move_operator)를 살펴보십시오. –

답변

2
class Matrix 
{ 

    struct Product 
    { 
     const Matrix* a; 
     const Matrix* b; 
    }; 

    Matrix& operator = (const Product& p) 
    { 
     // if this matrix dims differ from required by product of p.a and p.b 
     // reallocate it first and set dims 
     // {  
      // rows = ....; cols = ....; 
      // delete [] data; 
      // data = new [rows*cols]; 
     // } 


     // then calculate product 
     // data[0] = ...; 
     // ... 

     return *this; 

    } 

    Product operator * (const Matrix& op) const 
    { 
     Product p; 
     p.a = this; 
     p.b = &op; 
     return p; 
    } 

    int rows,cols; 
    double* data; 

    /// your Matrix stuff 
    // ... 
}; 

void test() 
{ 
    Matrix a(4,2),b(2,4),c; 

    c = a * b; // (note a*b returns Product without calculating its result 
       // result is calculated inside = operator 

    c = a * b; // note that this time c is initialized to correct size so no 
       // additional reallocations will occur 

} 
+0

검색 할 수있는 용어는 "표현 템플릿"http://en.wikipedia.org/wiki/Expression_templates입니다. –

+0

실제 제품 작업을 operator =? –

+0

우리는 제품 결과를 저장할 수있는 저장 공간을 기다려야하기 때문에. – Anonymous