Recent Posts
printf("ho_tari\n");
Array2 (template 지정) 본문
<main.cpp>
#include <iostream>
#include "array.h"
#include "complex.h"
int main() {
int nums1[] = {1,2,3,4,5};
Array<int>arr1(nums1, 5); // template (원하는 형태의 데이터타입 생성)
for (int i = 0; i<arr1.size(); ++i) {
std::cout << arr1[i] << std::endl;
}
double nums2[] = {1.1, 2.2, 3.3, 4.4, 5.5};
Array<double>arr2(nums2,5);
for (int i = 0; i<arr2.size(); ++i) {
std::cout << arr2[i] << std::endl;
}
Complex nums3[] = {Complex(3.0,4.0), Complex(3.0), Complex(), 3.0};
Array<Complex>arr3(nums3,4);
for (int i = 0; i<arr3.size(); ++i) {
std::cout << arr3[i] << std::endl;
}
return 0;
}
<array.h>
#ifndef ARRAY_H
#define ARRAY_H
#include <cassert>
template <typename T>
class Array { // 클래스,생성자,소멸자뒤에는 <T>를 붙이지 않는다.
private:
static const int ARRAYSIZE;
protected:
T *pArr_;
int size_;
public:
static int getDefaultSize();
//Array<T> *operator&() {return this;}
//const Array<T> *operator&() const { return this;}
//Array();
explicit Array(int size = Array<T>::ARRAYSIZE);
Array(const Array<T>& rhs);
Array(const T *pArr, int size);
virtual ~Array();
Array<T>& operator=(const Array<T>& rhs);
bool operator==(const Array<T>& rhs) const;
virtual T& operator[](int index);
virtual const T& operator[](int index) const;
int size() const;
};
template<typename T>
const int Array<T>::ARRAYSIZE = 100;
template<typename T>
int Array<T>::getDefaultSize() {
return Array<T>::ARRAYSIZE;
}
template<typename T>
Array<T>::Array(int size)
: pArr_(new T[size]),size_(size)
{
assert(pArr_);
}
template<typename T>
Array<T>::Array(const Array<T>& rhs)
:pArr_(new T[rhs.size_]),size_(rhs.size_)
{
assert(pArr_);
for (int i = 0; i<rhs.size(); i++) {
pArr_[i] = rhs.pArr_[i];
}
}
template<typename T>
Array<T>::Array(const T* pArr,int size)
:pArr_(new T[size]),size_(size)
{
assert(pArr_);
for (int i = 0; i<size; ++i) {
pArr_[i] = pArr[i];
}
}
template<typename T>
Array<T>::~Array() {
delete[] pArr_;
}
template<typename T>
Array<T>& Array<T>::operator=(const Array<T>& rhs) {
if (this != &rhs) {
delete[] pArr_;
pArr_ = new T[rhs.size_];
assert(pArr_);
size_ = rhs.size_;
for (int i = 0; i<rhs.size_; ++i) {
pArr_[i] = rhs.pArr_[i];
}
}
return *this;
}
template<typename T>
bool Array<T>::operator==(const Array<T>& rhs) const {
if (size_ != rhs.size_)
return false;
int i;
for (i = 0; i<rhs.size_; ++i) {
if (pArr_[i] != rhs.pArr_[i]) {
break;
}
}
return (i == rhs.size_);
}
template<typename T>
T& Array<T>::operator[](int index) {
return pArr_[index];
}
template<typename T>
const T& Array<T>::operator[](int index)const {
return pArr_[index];
}
template<typename T>
int Array<T>::size() const {
return size_;
}
#endif
'C++' 카테고리의 다른 글
Queue4 (template 지정) (0) | 2023.09.08 |
---|---|
Stack4 (template 지정) (0) | 2023.09.08 |
BoundArray (index 지정) (0) | 2023.09.08 |
Shape (RTTI : Run Time Type Identification) (0) | 2023.09.07 |
Shape (Shape, Rectangle, Circle 상속) (0) | 2023.09.07 |