1

マトリックス テンプレート クラスをコーディングしていますが、問題は、配列が作成されて値が入力されることですが、print() 関数を使用すると、配列が再び空になることです。誰かが私が間違っていることを教えてもらえますか?

データは次のように定義されます。

T **data; 


template<class T> 
CMatrix<T>::CMatrix( int rows, int cols)
{
setRow(rows);
setCol(cols);

data = new int*[rows];
// Create matrix with dimensions given

for (int i = 0; i < row; i++) {
    data[i] = new int [cols];
}

for(int i = 0; i < row; i++) {
    for(int j = 0; j < cols; j++) {
        data[i][j] = (int) i * j;
    }
}
}


template<class T> 
void CMatrix<T>::print()
{
int i,j;

for (i=0;i<4;i++)
{ 
for(j=0;j<4;j++)
{
    printf("%.1f    ",data[i][j]);
}
printf("\n");
}
}

主な機能:

int main (){    

int rows =4;
int cols = 4;

CMatrix<int>* matrixOne= new CMatrix<int>(rows, cols);
matrixOne->print();

    return(0);
}

テンプレートの宣言:

template<class T> 
class CMatrix

{
private:
    int row;  // number of rows
    int column;  // number of columns

public:     

    CMatrix(int rows, int cols);

    CMatrix(const CMatrix& data); //Copy constructor

    //Constructor taking an array of 16 elements
    CMatrix(T Matrix[16]);
    ~CMatrix();

    T **data; 
    void setRow(int r);
    void setCol(int c);
    int getRow();
    int getCol();

    //Subscript operators
    T& operator()(int row, int col);
    T operator()(int row, int col) const;
    void print();



};
4

1 に答える 1

3

クラスでデータ変数と行変数および列変数を使用していることを確認します。これは決して最も完全なバージョンではありませんが、コンパイルして正常に実行されます。

また、コンストラクターで「int」ではなく「T」を使用していることを確認してください。コメントを参照してください。

値をハードコーディングする代わりにrowとcolを使用することについてのprint関数の2つのコメントに注意してください。

#ifndef CMATRIX_H
#define CMATRIX_H

#include <stdio.h>

template <class T>
class CMatrix
{
public:
    CMatrix( int rows, int cols)
    {
        setRow(rows);
        setCol(cols);

        data = new T*[rows]; // replaced "int" for "T"

        for (int i = 0; i < row; i++) {
            data[i] = new T [cols]; // replaced "int" for "T"
        }

        for(int i = 0; i < row; i++) {
            for(int j = 0; j < cols; j++) {
                data[i][j] = (T) i * j; // replaced "int" for "T"
            }
        }
    }

    void print();
    void setRow(int r){row = r;}
    void setCol(int c){col = c;}
    T& operator()(int row, int col);
private:
    T **data;
    int row,col;
};

template <class T>
void CMatrix<T>::print ()
{
    int i,j;

    for (i=0;i < row;i++) // Here you used to have row hard coded to 4
    {
        for(j=0;j < col;j++) // Here you used to have col hard coded to 4
        {
            printf("%.1f    ",(float) data[i][j]);
        }
        printf("\n");
    }
}

// Recently added
template<class T> T& CMatrix<T>::operator()(int row, int col)
{
    return data[row][col];
}

#endif // CMATRIX_H

これがメインです。

#include "cmatrix.h"
#include <iostream>

int main(int argc, char *argv[])
{
    CMatrix <float> m(4,4);

    m.print();

    // Recently added
    std::cout << m(1,1);

    return 0;
}
于 2012-05-26T09:54:11.470 に答える