Recent Posts
printf("ho_tari\n");
SafeArray4 (try, throw, catch) 본문
<main.cpp>
#include <iostream>
#include "safeArray.h"
#include "invalidIndex.h"
int main()
{
int nums1[] = {1,2,3,4,5};
SafeArray<int> arr1(nums1,5);
for (int i = 0; i<5; i++)
{
std::cout << "arr1["<<i << "] : " << arr1[i] << std::endl;
}
try
{
double nums2[] = {1.1,2.2,3.3,4.4,5.5};
SafeArray<double> arr2(nums2,5);
for (int i = 0; i<5; i++)
{
std::cout << "arr2["<<i << "] : " << arr2[i] << std::endl;
}
arr2[5] = 6.6;
}
catch (const InvalidIndex& e)
{
std::cerr << "boundary exception. index : " << e.getIndex() << std::endl;
}
return 0;
}
<safeArray.h>
#ifndef SAFEARRAY_H
#define SAFEARRAY_H
#include <cassert>
#include "array.h"
#include "invalidIndex.h"
template <typename T>
class SafeArray:public Array<T> {
private:
public:
explicit SafeArray(int size = Array<T>::getDefaultSize());
SafeArray(const T *pArr, int size);
virtual ~SafeArray(){}
bool operator==(const SafeArray<T>& rhs) const;
T& operator[](int index);
const T& operator[](int index)const;
};
template <typename T>
SafeArray<T>::SafeArray(int size)
:Array<T>(size)
{
}
template <typename T>
SafeArray<T>::SafeArray(const T *pArr, int size)
:Array<T>(pArr,size)
{
}
template <typename T>
bool SafeArray<T>::operator==(const SafeArray<T>& rhs) const {
return this->Array<T>::operator==((Array<T>)rhs);
}
template <typename T>
T& SafeArray<T>::operator[](int index) {
//assert(index >= 0 && index < this->Array<T>::size_);
if (index < 0 || index >= this->Array<T>::size_)
throw InvalidIndex(index);
return this->Array<T>::operator[](index);
}
template <typename T>
const T& SafeArray<T>::operator[](int index) const{
//assert(index >= 0 && index < this->Array<T>::size_);
if (index < 0 || index >= this->Array<T>::size_)
throw InvalidIndex(index);
return this->Array<T>::operator[](index);
}
#endif
<invalidIndex.h>
#ifndef INVALIDINDEX_H
#define INVALIDINDEX_H
class InvalidIndex {
private:
int index_;
public:
InvalidIndex(int index);
int getIndex() const;
};
#endif
<invalidIndex.cpp>
#include "invalidIndex.h"
InvalidIndex::InvalidIndex(int index)
: index_(index)
{
}
int InvalidIndex::getIndex() const
{
return index_;
}
<compile 결과>
'C++' 카테고리의 다른 글
Pointer3 (reinterpret_cast) (0) | 2023.09.08 |
---|---|
GenderRatio (static_cast) (0) | 2023.09.08 |
BoundArray2 (template 사용) (0) | 2023.09.08 |
SafeArray3 (template 사용) (0) | 2023.09.08 |
Swap2 (template 사용) (0) | 2023.09.08 |