だから私の問題はこれです...私がポインタにメモリを割り当てようとしているとき、それは失敗します。
これは私のMatrixClass定義です。
class MatrixClass
{
public:
MatrixClass(int m, int n);
MatrixClass(void);
virtual ~MatrixClass(void);
double getRead(int num1, int num2) const;
double& getReadWrite(int num3, int num4);
void set(int i,int j,double value);//set value at i,j to value
MatrixClass(const MatrixClass &rhs);
void assign(int M,int N);
MatrixClass sum1(const MatrixClass& rhs) const;
MatrixClass operator+(const MatrixClass& rhs);//overloading the + operator
MatrixClass operator-();
private:
double* dataptr;
int M;
int N;
};
私はこれをやろうとしています。
MatrixClass BB;
BB = A + B;
これが私のオーバーロードされた+関数です。
MatrixClass MatrixClass::operator +(const MatrixClass &rhs)
{
MatrixClass temp;
//temp.M = this->M + rhs.M;
//temp.N = this->N + rhs.N;
for(int i = 0;i < M;i++)
{
for(int j = 0; j<N;j++)
{
temp.dataptr[i * N + j] = this->getReadWrite(i,j) + rhs.dataptr[i*N+j];
}
}
return temp;
}//end operator +
tempが戻ると...コピーコンストラクターを呼び出します...tempを「rhs」として渡し、「this」は「BB」を参照しますか?(私はこれを考えるのは正しいですか?)
MatrixClass::MatrixClass(const MatrixClass &rhs)//copy constructor
{
this->M = rhs.M;
this->N = rhs.N;
dataptr = 0;
if(rhs.dataptr != 0)
{
dataptr = new double[M * N];//allocate memory for the new object being assigned to...
// the line here where I try to allocate memory gives me an error.....Am I right in
//thinking that this would be assigning memory to dataptr of 'BB'?? Values are assigned to //'M' and 'N' fine....
int num = sizeof(double);
memcpy(this->dataptr,rhs.dataptr,M*N*sizeof(double));
}
else
{
this->dataptr = 0;
}
}//end copy constructor
また、私が得るエラーはこれです...'assignment.exeの0x75a0b727での未処理の例外:Microsoft C ++例外:メモリ位置0x002af924のstd :: bad_alloc ..'
だから基本的に私が尋ねている質問は..なぜ地獄は私が問題を与えているコピーコンストラクターの'dataptr'にメモリを割り当てようとしている行です..それは戻り値からコピーコンストラクターを呼び出すときにのみこれを行います'temp' ..
ありがとう!