| この問題を解くためには… |
| → 基本編第5日目参照 |
|---|
問題5:静的メンバ
prob5-1.(難易度:★)
以下のクラスの静的メンバ関数を実装した、function.cppをついかし、期待される実行結果通りの結果が得られるように改造しなさい。
prob5-1:function.h
#ifndef _FUNCTION_H_
#define _FUNCTION_H_
class Function{
public:
// 最大値を返す関数
static int max(int n1, int n2);
// 最小値を返す関数
static int min(int n1, int n2);
};
#endif // _FUNCTION_H_
#include <iostream>
#include "function.h"
using namespace std;
int main(){
int m = 3, n = 1;
cout << m << "と" << n << "のうち、最大のものは" << Function::max(m, n) << endl;
cout << m << "と" << n << "のうち、最大のものは" << Function::min(m, n) << endl;
return 0;
}
3と1のうち、最大のものは3
3と1のうち、最小のものは1
3と1のうち、最小のものは1
prob5-2.(難易度:★)
次のプログラムの、クラスObjectは、生成したオブジェクトの数を、静的メンバ変数m_objectNumで数えている。このクラスに、m_objectNumの値を取得するint型の静的メンバ関数getObjectNum()を追加し、プログラムを、期待される実行結果が得られるように変更しなさい。
prob5-2:object.h
#ifndef _OBJECT_H_
#define _OBJECT_H_
class Object{
private:
static int m_objectNum;
public:
// コンストラクタ
Object();
// デストラクタ
~Object();
};
#endif // _OBJECT_H_
#include "object.h"
// 静的メンバ変数の初期値を設定
int Object::m_objectNum = 0;
// コンストラクタ
Object::Object()
{
// オブジェクトの数をカウントする
m_objectNum++;
}
// デストラクタ
Object::~Object()
{
// オブジェクトの数をカウントする
m_objectNum--;
}
#include <iostream>
#include "object.h"
using namespace std;
int main(){
Object *o1, *o2, *o3;
o1 = new Object();
o2 = new Object();
o3 = new Object();
cout << "オブジェクトの数:" << Object::getObjectNum() << endl;
delete o3;
cout << "オブジェクトの数:" << Object::getObjectNum() << endl;
delete o2;
delete o1;
return 0;
}
オブジェクトの数:3
オブジェクトの数:2
オブジェクトの数:2
prob5-3.(難易度:★★)
以下のプログラムは、カウンタークラスCountを使用したプログラムである。このプログラムを、指定されたように変更しなさい。
prob5-2:counter.h
#ifndef _COUNTER_H_
#define _COUNTER_H_
class Counter{
private:
// 回数
int m_count;
public:
// コンストラクタ
Counter();
// リセット
void reset();
// カウント
void count();
// カウントの数
int getCount();
};
#endif // _COUNTER_H_
#include "counter.h"
// コンストラクタ(カウント回数を0で初期化)
Counter::Counter() : m_count(0)
{
}
void Counter::reset(){
m_count = 0;
}
void Counter::count(){
m_count++;
}
int Counter::getCount(){
return m_count;
}
#include <iostream>
#include "counter.h"
using namespace std;
int main(){
Counter c1, c2;
c1.count();
c2.count();
c2.count();
c2.reset();
c1.count();
c1.count();
c2.count();
cout << "c1のカウント数:" << c1.getCount() << endl;
cout << "c2のカウント数:" << c2.getCount() << endl;
cout << "トータルのカウント数:" << c1.getCount() + c2.getCount() << endl;
return 0;
}
c1のカウント数:3
c2のカウント数:1
トータルのカウント数:4
c2のカウント数:1
トータルのカウント数:4
main.cppの18行目に出ている、c1.getCount() + c2.getCount()を、クラスCounterの静的メソッドによって出力できるようにプログラムを改造しなさい。その際、以下のようにクラスCounterを変更すること。
Counterクラスの変更ポイント- 作成する静的メンバ関数の名前は、getTotalCount()とする。(戻り値はint)
- この関数内では、トータルのカウント回数を記録した静的メンバ変数を、m_totalCountとする。









