| IntArray.h |
|---|
// IntArray.h
#ifndef __INTARRAY_H_INCLUDED__
#define __INTARRAY_H_INCLUDED__
#include <stddef.h>
class CIntArray
{
// メンバ変数
private:
int* m_pnum; // 動的配列
int m_nNumOf; // 配列の要素数
// コンストラクタ・デストラクタ
public:
CIntArray(const int nNumOf);
CIntArray(const CIntArray& rother); // コピーコンストラクタ
~CIntArray();
// メンバへのアクセス関数
public:
int Get(const int index) const;
void Set(const int index, const int value);
// インデックスのチェック
private:
void CheckIndex(const int index) const;
// その他の情報の取得
public:
bool Success() const; // メモリの確保が成功したか
int NumOf() const; // 配列の要素数
int SizeOf() const; // 配列のサイズ
};
// メモリの確保が成功したか
inline bool CIntArray::Success() const
{
return m_pnum != NULL;
}
// 配列の要素数
inline int CIntArray::NumOf() const
{
return m_nNumOf;
}
// 配列のサイズ
inline int CIntArray::SizeOf() const
{
return m_nNumOf * sizeof *m_pnum;
}
#endif |
| IntArray.cpp |
// IntArray.cpp
#include <iostream.h>
#include <memory.h>
#include <process.h>
#include "IntArray.h"
// コンストラクタ
CIntArray::CIntArray(const int nNumOf)
{
m_pnum = new int[nNumOf];
if(m_pnum == NULL)
m_nNumOf = 0;
else
{
m_nNumOf = nNumOf;
memset(m_pnum, 0, nNumOf * sizeof *m_pnum);
}
cout << "コンストラクタが呼ばれました。"
<< "要素数は " << m_nNumOf << " です。" << endl;
}
// コピーコンストラクタ
CIntArray::CIntArray(const CIntArray& rother)
{
if(rother.Success() == false)
{
m_pnum = NULL;
m_nNumOf = 0;
}
else
{
m_pnum = new int[rother.NumOf()];
if(m_pnum == NULL)
{
m_nNumOf = 0;
return;
}
// memcpy はメモリの内容をバイト単位でコピーする関数です
memcpy(m_pnum, rother.m_pnum, rother.SizeOf());
m_nNumOf = rother.m_nNumOf;
}
cout << "コピーコンストラクタが呼ばれました。" << endl;
}
// デストラクタ
CIntArray::~CIntArray()
{
if(m_pnum != NULL)
delete [] m_pnum;
cout << "デストラクタが呼ばれました。"
<< "要素数は " << m_nNumOf << " でした。" << endl;
}
// メンバへのアクセス関数
int CIntArray::Get(const int index) const
{
CheckIndex(index);
return m_pnum[index];
}
void CIntArray::Set(const int index, const int value)
{
CheckIndex(index);
m_pnum[index] = value;
}
// インデックスのチェック
void CIntArray::CheckIndex(const int index) const
{
if((unsigned int)index < (unsigned int)m_nNumOf)
return;
cout << "インデックスが不正です!" << endl
<< "値 : " << index << endl;
exit(1);
} |
Last update was done on 2000.8.27
この講座の著作権はロベールが保有しています