Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- SNS
- Reflex
- 코딩독학
- 백준
- 주가예측
- 코테
- 개발
- 자바정리
- frontend
- backend
- Python
- Project
- 자바
- 빅데이터
- 프로그래머스
- 개발자
- 프로그램
- 모의 주식
- 개인프로젝트
- 코딩
- java
- C++
- 코스닥
- 프로그래밍
- 코딩테스트
- 이웃한 칸
- 사물인터넷
- 자바독학
- java정리
- 풀스택프레임워크
Archives
- Today
- Total
Creative Code
safeArray4(try-throw-catch) 본문
※main.cpp파일
#include <iostream>
#include "safeArray.h"
#include "array.h"
#include "invalidindex.h"
int main() {
int nums1[] = {1,2,3,4,5};
SafeArray 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 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;
//handling!
}
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;
virtual T& operator[](int index);
virtual 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_;
protected:
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_;
}
'C++ Programming' 카테고리의 다른 글
pointer3.cpp(reinterpret_cast) (0) | 2023.09.08 |
---|---|
genderRatio.cpp(static_cast) (0) | 2023.09.08 |
swap2(template 함수) (0) | 2023.09.08 |
boundArray2(template사용) (0) | 2023.09.08 |
safeArray3(template 사용) (0) | 2023.09.08 |