Recent Posts
printf("ho_tari\n");
SafeArray 본문
<main.cpp>
#include <iostream>
#include "safeArray.h"
#include "array.h"
int main()
{
SafeArray arr1;
SafeArray arr2(100);
int nums[] = {1,2,3,4,5};
SafeArray arr3(nums,5);
const SafeArray arr4 = arr3;
arr1 = arr4;
if (arr1 == arr4)
{
std::cout << "arr1 and arr4 are equal" << std::endl;
}
else
{
std::cout << "arr1 and arr4 are not equal" << std::endl;
}
arr1[0] = arr1[4];
for (int i = 0; i<arr1.size(); ++i)
{
std::cout << arr1[i] << " "; //arr1.operator[](i)
}
std::cout << std::endl;
return 0;
}
<safeArray.h>
#ifndef SAFEARRAY_H
#define SAFEARRAY_H
#include "array.h"
class SafeArray : public Array {
private:
public:
explicit SafeArray(int size = Array::getDefaultSize());
SafeArray(const int *pArr, int size);
//SafeArray(const SafeArray& rhs);
//~SafeArray();
//SafeArray& operator=(const SafeArray& rhs);
bool operator==(const SafeArray& rhs) const;
int& operator[](int index);
const int& operator[](int index) const;
};
#endif
<safeArray.cpp>
#include "safeArray.h"
#include <cassert>
SafeArray::SafeArray(int size)
: Array(size)
{
}
SafeArray::SafeArray(const int *pArr, int size)
: Array(pArr, size)
{
}
/*
SafeArray::SafeArray(const SafeArray& rhs)
: Array( (Array)rhs) // slicing
{
}
SafeArray::~SafeArray()
{
// automatically Array::~Array() is called
}
SafeArray& SafeArray::operator=(const SafeArray& rhs)
{
this->Array::operator=( (Array)rhs);
return *this;
}
*/
bool SafeArray::operator==(const SafeArray& rhs) const
{
return this->Array::operator==( (Array)rhs);
}
int& SafeArray::operator[](int index)
{
assert(index >= 0 && index < this->Array::size());
return this->Array::operator[](index);
}
const int& SafeArray::operator[](int index) const
{
assert(index >= 0 && index < this->Array::size());
return this->Array::operator[](index);
}
<compile 결과>
'C++' 카테고리의 다른 글
Shape (Shape, Rectangle, Circle 상속) (0) | 2023.09.07 |
---|---|
SafeArray2 (상속) (0) | 2023.09.07 |
Queue3 (array 클래스와 has-a 관계) (0) | 2023.09.07 |
Queue2 (생성자 초기화 리스트, static member, explicit) (0) | 2023.09.07 |
Stack2 (extern, explicit) (0) | 2023.09.07 |