-1

クラス プロジェクトの場合、ポインターの 2D 配列があります。コンストラクタ、デストラクタなどは理解していますが、配列に値を設定する方法を理解するのに問題があります。オーバーロードされた入力演算子を使用して値を入力しています。これまでのところ、その演算子のコードは次のとおりです。

istream& operator>>(istream& input, Matrix& matrix) 
{
bool inputCheck = false;
int cols;

while(inputCheck == false)
{
    cout << "Input Matrix: Enter # rows and # columns:" << endl; 

    input >> matrix.mRows >> cols;
    matrix.mCols = cols/2;

    //checking for invalid input
    if(matrix.mRows <= 0 || cols <= 0)
    {
        cout << "Input was invalid. Try using integers." << endl;
        inputCheck = false;
    }
    else
    {
        inputCheck = true;
    }

    input.clear();
    input.ignore(80, '\n');
}

if(inputCheck = true)
{
    cout << "Input the matrix:" << endl;

    for(int i=0;i< matrix.mRows;i++) 
    {
        Complex newComplex;
        input >> newComplex; 
        matrix.complexArray[i] = newComplex; //this line
    }
}
return input;
}

ここにある割り当てステートメントは明らかに間違っていますが、どのように機能するのかわかりません。さらにコードを含める必要がある場合は、お知らせください。メイン コンストラクタは次のようになります。

Matrix::Matrix(int r, int c)
{
if(r>0 && c>0)
{
    mRows = r;
    mCols = c;
}
else
{
    mRows = 0;
    mCols = 0;
}

if(mRows < MAX_ROWS && mCols < MAX_COLUMNS)
{
    complexArray= new compArrayPtr[mRows];

    for(int i=0;i<mRows;i++)
    {
        complexArray[i] = new Complex[mCols];
    }
}
}

ここに Matrix.h があるので、属性を確認できます。

class Matrix
{
friend istream& operator>>(istream&, Matrix&);

friend ostream& operator<<(ostream&, const Matrix&);

private:
    int mRows;
    int mCols;
    static const int MAX_ROWS = 10;
    static const int MAX_COLUMNS = 15;
    //type is a pointer to an int type
    typedef Complex* compArrayPtr;
    //an array of pointers to int type
    compArrayPtr *complexArray;

public:

    Matrix(int=0,int=0);
            Matrix(Complex&);
    ~Matrix();
    Matrix(Matrix&);

};
#endif

私が得ているエラーは、「割り当てでComplexをMatrix::compArrayPtr(別名Complex *)に変換できません」です。私が間違っていることを誰かが説明できれば、とても感謝しています。

4

1 に答える 1

1

あなたnewComplexは型 (値) のオブジェクトであり、それをポインターComplexに割り当てようとしています。Complex*

これが機能するには、複合体を動的に構築する必要があります。

Complex* newComplex = new Complex();
input >> *newComplex;
matrix.complexArray[i] = newComplex;

ただし、動的割り当てに伴うすべての結果 (メモリ管理、所有権、共有状態など) に注意してください。

于 2013-04-27T18:37:05.300 に答える