// arrover3.cpp
// creates safe array (index values are checked before access)
// uses overloaded [] operator for both put and get
#include <iostream>
using namespace std;
#include <process.h> //for exit()
const int LIMIT = 100; //array size
////////////////////////////////////////////////////////////////
class safearay
{
private:
int arr[LIMIT];
public:
int& operator [](int n) //note: return by reference
{
if( n< 0 || n>=LIMIT )
{ cout << "\nIndex out of bounds"; exit(1); }
return arr[n];
}
};
////////////////////////////////////////////////////////////////
int main()
{
safearay sa1;
for(int j=0; j<LIMIT; j++) //insert elements
sa1[j] = j*10; //*left* side of equal sign
for(j=0; j<LIMIT; j++) //display elements
{
int temp = sa1[j]; //*right* side of equal sign
cout << "Element " << j << " is " << temp << endl;
}
return 0;
}
ООП С++. Р.Лафоре. Глава 8, задача 9, решил но криво, какие есть альтернативы?
Задача:
Цитата:
Дополните класс safearray из программы ARROVER3 этой главы так, чтобы пользователь мог определять и верхнюю, и нижнюю границы массива (например, индексы, начинающиеся с 100 и заканчивающиеся 200). Имеем перегруженную операцию доступа к членам массива, проверяющую индексы каждый раз, когда массиву нужен доступ, для проверки того, что мы не вышли за пределы массива. Вам понадобится конструктор с двумя аргументами, который определяет верхнюю и нижнюю границы. Так как мы еще не изучили, как выделять память динамически, то данные класса все еще будут размещаться в массиве, состоящем из 100 элементов, но вообще вы можете преобразовывать индексы массива safearray в индексы реального массива целых чисел произвольным образом. Например, если пользователь определил диапазон от 100 до 175, то вы можете преобразовать его в диапазон от arr[0] до arr[75].
Листинг ARROVER3
Код:
Мое решение:
Код:
// arrover3.cpp
// creates safe array (index values are checked before access)
// uses overloaded [] operator for both put and get
#include <iostream>
using namespace std;
#include <process.h> //for exit()
const int LIMIT = 100; //array size
////////////////////////////////////////////////////////////////
class safearray
{
private:
int A;
int B;
int arr[LIMIT];
public:
safearray ():A(0),B(100)
{}
safearray (int a, int b)
{
if (a>=100 && b>100)
{
int c=b-a;
A=0;
B=c;
}
if (a>=0 && b<=LIMIT)
{
A=a; B=b;
}
}
int getA() { return A; }
int getB() { return B; }
int& operator [](int n) //note: return by reference
{
if( n< 0 || n>=LIMIT )
{ cout << "\nIndex out of bounds"; exit(1); }
return arr[n];
}
};
////////////////////////////////////////////////////////////////
int main()
{
safearray sa1(10,75);
for(int j=sa1.getA(); j<=sa1.getB(); j++) //insert elements
sa1[j] = j*10; //*left* side of equal sign
for(j=sa1.getA(); j<=sa1.getB(); j++) //display elements
{
int temp = sa1[j]; //*right* side of equal sign
cout << "Element " << j << " is " << temp << endl;
}
return 0;
}
// creates safe array (index values are checked before access)
// uses overloaded [] operator for both put and get
#include <iostream>
using namespace std;
#include <process.h> //for exit()
const int LIMIT = 100; //array size
////////////////////////////////////////////////////////////////
class safearray
{
private:
int A;
int B;
int arr[LIMIT];
public:
safearray ():A(0),B(100)
{}
safearray (int a, int b)
{
if (a>=100 && b>100)
{
int c=b-a;
A=0;
B=c;
}
if (a>=0 && b<=LIMIT)
{
A=a; B=b;
}
}
int getA() { return A; }
int getB() { return B; }
int& operator [](int n) //note: return by reference
{
if( n< 0 || n>=LIMIT )
{ cout << "\nIndex out of bounds"; exit(1); }
return arr[n];
}
};
////////////////////////////////////////////////////////////////
int main()
{
safearray sa1(10,75);
for(int j=sa1.getA(); j<=sa1.getB(); j++) //insert elements
sa1[j] = j*10; //*left* side of equal sign
for(j=sa1.getA(); j<=sa1.getB(); j++) //display elements
{
int temp = sa1[j]; //*right* side of equal sign
cout << "Element " << j << " is " << temp << endl;
}
return 0;
}
Что-то мне не нравится результат, возможно автор подразумевал использование перегрузки операторов в решении этой задачи..
Как можно корректнее ее решит?
Код:
// arrover3.cpp
// creates safe array (index values are checked before access)
// uses overloaded [] operator for both put and get
#include <iostream>
using namespace std;
#include <process.h> //for exit()
const int LIMIT = 100; //array size
////////////////////////////////////////////////////////////////
class SafeArray
{
private:
int Arr[LIMIT];
unsigned DownLimit;
unsigned UpLimit;
public:
SafeArray(): DownLimit(0), UpLimit(LIMIT)
{}
SafeArray(unsigned Down, unsigned Up)
{
if (Down > Up)
{
unsigned uiBuffer = Up;
Up = Down;
Down = uiBuffer;
}
if (Up - Down > LIMIT) Up = Down + LIMIT;
DownLimit = Down;
UpLimit = Up;
}
int& operator [](unsigned n) //note: return by reference
{
if (n < DownLimit || n >= UpLimit)
{
cout << "\nIndex out of bounds";
exit(1);
}
return Arr[[COLOR="Red"]n - DownLimit[/COLOR]];
}
};
// creates safe array (index values are checked before access)
// uses overloaded [] operator for both put and get
#include <iostream>
using namespace std;
#include <process.h> //for exit()
const int LIMIT = 100; //array size
////////////////////////////////////////////////////////////////
class SafeArray
{
private:
int Arr[LIMIT];
unsigned DownLimit;
unsigned UpLimit;
public:
SafeArray(): DownLimit(0), UpLimit(LIMIT)
{}
SafeArray(unsigned Down, unsigned Up)
{
if (Down > Up)
{
unsigned uiBuffer = Up;
Up = Down;
Down = uiBuffer;
}
if (Up - Down > LIMIT) Up = Down + LIMIT;
DownLimit = Down;
UpLimit = Up;
}
int& operator [](unsigned n) //note: return by reference
{
if (n < DownLimit || n >= UpLimit)
{
cout << "\nIndex out of bounds";
exit(1);
}
return Arr[[COLOR="Red"]n - DownLimit[/COLOR]];
}
};
Код:
if (Up - Down > LIMIT) Up = Down + LIMIT;
DownLimit = Down;
UpLimit = Up;
DownLimit = Down;
UpLimit = Up;
Может не хватает кавычек?
Код:
if (Up - Down > LIMIT)
{
Up = Down + LIMIT;
}
else
{
DownLimit = Down;
UpLimit = Up;
}
{
Up = Down + LIMIT;
}
else
{
DownLimit = Down;
UpLimit = Up;
}
Код:
#include <iostream>
using namespace std;
#include <process.h> // для функции exit
const int LIMIT = 100; // размер массива
///////////////////////////////////////////////////////////
class safearray
{
private:
int arr[LIMIT];
int buttom, top;
public:
safearray(int b, int t) //аргументы - границы массива
{
if (t - b>LIMIT) {cout<<"Repletion!n "; exit(1);}
while(b>LIMIT)
{ b -= LIMIT; t -=LIMIT ;}
buttom = b; top = t;
}
/////////////////////////////////////////
int& operator[](int n)// обратите внимание, что функция возвращает ссылку!
{
while(n>LIMIT)
n -= LIMIT;
if(n < buttom || n >= top)
{ cout << "nRong index!n"; exit(1); }
return arr[n];
}
//////////////////////////////////////////
};
///////////////////////////////////////////////////////////
int main()
{
int Top, Buttom;
cout<<" Put limit of array: ";
cin>>Buttom>>Top;
safearray sa1(Buttom, Top);
int ind, val;
for (int j=0; j<4; j++) // задаем значения элементов
{cout<<"Put index and value: ";
cin>>ind>>val;
sa1[ind]= val;
}
for (int g=0; g<4; g++) // показываем элементы
{ cout<<"nPut index: ";
cin>>ind;
int temp = sa1[ind];
cout<<" Value is: "<< temp << endl;
}
cout<< endl;
return 0;
}
using namespace std;
#include <process.h> // для функции exit
const int LIMIT = 100; // размер массива
///////////////////////////////////////////////////////////
class safearray
{
private:
int arr[LIMIT];
int buttom, top;
public:
safearray(int b, int t) //аргументы - границы массива
{
if (t - b>LIMIT) {cout<<"Repletion!n "; exit(1);}
while(b>LIMIT)
{ b -= LIMIT; t -=LIMIT ;}
buttom = b; top = t;
}
/////////////////////////////////////////
int& operator[](int n)// обратите внимание, что функция возвращает ссылку!
{
while(n>LIMIT)
n -= LIMIT;
if(n < buttom || n >= top)
{ cout << "nRong index!n"; exit(1); }
return arr[n];
}
//////////////////////////////////////////
};
///////////////////////////////////////////////////////////
int main()
{
int Top, Buttom;
cout<<" Put limit of array: ";
cin>>Buttom>>Top;
safearray sa1(Buttom, Top);
int ind, val;
for (int j=0; j<4; j++) // задаем значения элементов
{cout<<"Put index and value: ";
cin>>ind>>val;
sa1[ind]= val;
}
for (int g=0; g<4; g++) // показываем элементы
{ cout<<"nPut index: ";
cin>>ind;
int temp = sa1[ind];
cout<<" Value is: "<< temp << endl;
}
cout<< endl;
return 0;
}