2014-06-29 3 views
-1

У меня очень странная проблема при создании объекта класса «CorrelatedNormalGenerator». См. Код ниже. Матрица класса используется классом CorrelatedNormalGenerator. Заранее спасибо за вашу помощь.Ошибка объявления объекта

в Matrix.h

#include <string> 
    #include <vector> 

    using namespace std; 


    template <typename T, typename I> 
    class Matrix 
    { 

     private: 

     vector<vector<T> > M; 
     I minRowIndex, maxRowIndex; 
     I minColIndex, maxColIndex; 
     I rowNumber, colNumber; 



     public: 

     Matrix(); // default constructor 

     Matrix(const I& _rowNumber, 
       const I& _colNumber, 
       const T& value = 0.0, 
        const I& _minRowIndex = 0, 
        const I& _minColIndex = 0); 

     Matrix<T,I>& operator = (const Matrix<T,I>& N); 
    Matrix(const Matrix<T,I>& N); // copy constructor, 
    virtual ~Matrix(){}; 



     T& operator() (const I& row, const I& col); 

     const T& operator() (const I& row, const I& col) const; 


}; 

template<typename T, typename I> 
Matrix<T,I> :: Matrix(const Matrix<T,I>& N) 
{ 
    M = N.M; 
    rowNumber = N.GetRows(); 
    colNumber = N.GetCols(); 
    minRowIndex = N.minRowIndex; 
    minColIndex = N.minColIndex; 
    maxRowIndex = N.minRowIndex + N.rowNumber - 1; 
    maxColIndex = N.minColIndex + N.colNumber - 1; 
} 



template<typename T, typename I> 
Matrix<T,I> :: Matrix(const I& _rowNumber, 
        const I& _colNumber, 
        const T& value, 
        const I& _minRowIndex, 
        const I& _minColIndex) 

{ 
    minRowIndex = _minRowIndex; 
    minColIndex = _minColIndex; 

    maxRowIndex = _minRowIndex + _rowNumber - 1; 
    maxColIndex = _minColIndex + _colNumber - 1; 

    rowNumber = _rowNumber; 
    colNumber = _colNumber; 

M.resize(rowNumber); 

for (I i = minRowIndex ; i < rowNumber; i++) 
    M[i].resize(colNumber, value); 

} 

template<typename T, typename I> 
T& Matrix<T,I> :: operator() (const I& row, const I& col) 
{ 
    return M[row][col]; 
} 

// Access the individual elements (const) 

template<typename T, typename I> 
const T& Matrix<T,I> :: operator() (const I& row, const I& col) const 
{ 
    return M[row][col]; 
} 


template<typename T, typename I> 
Matrix<T,I>& Matrix<T,I> :: operator = (const Matrix<T,I>& N) 
{ 
    rowNumber = N.GetRows(); 
    colNumber = N.GetCols(); 
    minRowIndex = N.minRowIndex; 
    minColIndex = N.minColIndex; 
    maxRowIndex = N.minRowIndex + N.rowNumber - 1; 
    maxColIndex = N.minColIndex + N.colNumber - 1; 

    M.resize(rowNumber); 
    I i,j; 

    for (i= minRowIndex; i <= maxRowIndex; i++) 
    { 
     M[i].resize(colNumber); 
    } 

    for (i= minRowIndex; i <= maxRowIndex; i++) 
    { 
     for (j = minColIndex; j <= maxColIndex; j++) 
     { 
      M[i][j] = N(i,j); 
     } 
    } 

    return *this; 
} 

в CorrelatedNormalGenerator.h

#include "Matrix.h" 
#include <cmath> 
using namespace std; 


template <typename T, typename I> // I = paramanter of matrix 
class CorrelatedNormalGenerator 
{ 

    private: 
     Matrix <T,I> SIGMA; // covariance matrix 



    public: 

     CorrelatedNormalGenerator(Matrix <T,I>& _SIGMA); 


     vector <T> GetCorrVectorSingleAsset(const vector<T>& uncorrVector1, 
            const vector<T>& uncorrVector2); 

     vector <T> GetCorrVectorMultiAsset(const vector<T>& uncorrVector); 

     virtual ~CorrelatedNormalGenerator(){}; 

}; 

template <typename T, typename I> 
CorrelatedNormalGenerator<T,I> :: CorrelatedNormalGenerator(Matrix <T,I>& _SIGMA) 
{ 
    SIGMA =_SIGMA; 
} 



template <typename T, typename I> 
vector <T> CorrelatedNormalGenerator<T,I> :: GetCorrVectorMultiAsset(const vector<T>& uncorrVector) 
{ 
     Matrix<T,I> Chol = SIGMA.Cholesky(); 

     return Chol*uncorrVector; 
} 

template <typename T, typename I> 
vector <T> CorrelatedNormalGenerator<T,I> :: GetCorrVectorSingleAsset(const vector<T>& uncorrVector1, const vector<T>& uncorrVector2) 
{ 
     vector<T> corrVector(uncorrVector1.size()); 

     for (unsigned i = 0; i < uncorrVector1.size(); i++) 
      corrVector[i] = rho*uncorrVector1[i] + sqrt(1- rho*rho)*uncorrVector2[i]; 

     return corrVector; 
} 

в main.cpp

#include "CorrelatedNormalGenerator.h" 

    using namespace std; 

    int main() 
    { 

    Matrix<double, int> P (3,3,0.0); 

    P(0,0) = 1.0; 
    P(1,1) = 1.0; 
    P(2,2) = 1.0; 
    P(1,2) = P(2,1) = 0.5; 
    P(0,1) = P(1,0) = 0.6; 
    P(0,2) = P(2,0) = 0.3; 

    CorrelatedNormalGenerator<double, int> gen(P); // ERROR: MAIN.cpp MAIN.obj : error LNK2019: unresolved external symbol "public: __thiscall Matrix<double,int>::Matrix<double,int>(void)" ([email protected]@@[email protected]) referenced in function "public: __thiscall CorrelatedNormalGenerator<double,int>::CorrelatedNormalGenerator<double,int>(class Matrix<double,int> &)" ([email protected]@@[email protected][email protected]@@@Z) 

    return 0; 
    } 
+0

его говорит вам, что вы не реализовали конструктор по умолчанию Matrix, и я не вижу его в коде, который вы опубликовали. Запишите код Matrix :: Matrix (). – DNT

+0

Спасибо, сейчас работает! Не могли бы вы объяснить, почему в этом случае конструктор по умолчанию был обязательным? Как я могу понять, когда мне это нужно, а когда нет? Спасибо – user3705076

+0

, потому что, поскольку вы не инициализировали матрицу в списке инициализации конструктора, она пытается вызвать конструктор по умолчанию ('Matrix ()'), который не определен, даже если он объявлен. Сделайте его приватным или удалите, чтобы намекнуть, что он не будет использоваться, если у вас есть совместимый с C++ 11 компилятор ('Matrix() = delete;') – Creris

ответ

1

Это говорит вам, что вы не выполнили конструктор по умолчанию Matrix , и я не вижу его в коде, который вы опубликовали. Добавьте код для

Matrix<T,I>::Matrix<T,I>() 

Это необходимо потому, что вы задаете матрицу в CorrelatedNormalGenerator без его инициализации в списке инициализации, используя один из другого матричного ctors, следовательно, необходимости по умолчанию CTOR:

private: 
    Matrix <T,I> SIGMA; // covariance matrix 
+0

Я бы хотел добавить что 'CorrelatedNormalGenerator' заполняет экземпляр« Matrix », копируя его. Использование списка инициализаторов позволит избежать создания бесполезной по умолчанию версии, которая впоследствии будет перезаписана. –

Смежные вопросы