-5
代碼正在編譯,但控制檯窗口消失。在print()函數中是否有錯誤,或者是編譯器(Dev C++)? 我嘗試以許多不同的方式在main()函數中打印,但其中一些代碼在此代碼工作時給我提供了錯誤。2D安全數組C++
#include<iostream>
#include<cstdlib>
#include<cassert>
using namespace std;
const int ROW = 2;
const int COL = 2;
template<class T> class SA
{
private:
int low, high;
T* p;
public:
// default constructor
SA()
{
low = 0;
high = -1;
p = NULL;
}
// 2 parameter constructor lets us write
SA(int l, int h)
{
if ((h - l + 1) <= 0)
{
cout << "constructor error in bounds definition" << endl;
exit(1);
}
low = l;
high = h;
p = new T[h - l + 1];
}
// single parameter constructor lets us
// SA x(10); and getting an array x indexed from 0 to 9
SA(int i)
{
low = 0;
high = i - 1;
p = new T[i];
}
// copy constructor for pass by value and
// initialization
SA(const SA & s)
{
int size = s.high - s.low + 1;
p = new T[size];
for (int i = 0; i < size; i++)
p[i] = s.p[i];
low = s.low;
high = s.high;
}
// destructor
~SA()
{
delete[] p;
}
//overloaded [] lets us write
//SA x(10,20); x[15]= 100;
T& operator[](int i)
{
if (i < low || i > high)
{
cout << "index " << i << " out of range" << endl;
exit(1);
}
return p[i - low];
}
// overloaded assignment lets us assign one SA to another
SA & operator=(const SA & s)
{
if (this == &s)
return *this;
delete[] p;
int size = s.high - s.low + 1;
p = new T[size];
for (int i = 0; i < size; i++)
p[i] = s.p[i];
low = s.low;
high = s.high;
return *this;
}
// overloads << so we can directly print SAs
friend ostream& operator<<(ostream& os, SA s)
{
int size = s.high - s.low + 1;
for (int i = 0; i < size; i++)
cout << s.p[i] << endl;
return os;
};
//end of ostream
};
//end class of safeArray
//Matrix class
template<class T> class Matrix
{
private:
SA<SA<T> > matrx;
public:
//2 param for 2D array
Matrix(int r, int c)
{
matrx = SA<SA<T> >(0, r - 1);
for (int i = 0; i < r; i++)
{
matrx[i] = SA<T>(0, c - 1);
}
}
SA<T> operator[](int row)
{
return (matrx[row]);
}
void read()
{
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
cin >> this->s[i][j];
}
void print()
{
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
cout << this->s[i][j] << "\t" << endl;
}
};
//class Matrix
int main()
{
Matrix<int> A(2, 2);
A[0][2] = 5;
cout << A[0][2];
//A.print();
/*
Matrix <int> A;
cout<<"Enter matrix A:"<<endl;
A.read();
cout<<"Matrix A is: "<<endl;
A.print();
*/
system("PAUSE");
return 0;
}
請縮進。 –
如果'new'在賦值運算符中引發異常,則此數組不再是「安全」。你爲什麼通過調用'exit()'退出整個應用程序,只是因爲構造函數的參數不正確? – PaulMcKenzie
我們可以安全地假設這個任務不允許使用「std :: vector」嗎? – user4581301