前章ではクラスの定義と使い方を学びました。
この章では、クラスの中に含まれる「メンバ変数」と「メンバ関数」について、
その意味や使い方をさらに深く理解します。
メンバ変数は、クラスの中にあるデータ(変数)です。
それぞれのオブジェクトが自分だけの値を持つことができます。
// 10_member_variable.cpp
#include <iostream>
using namespace std;
class Dog {
public:
string name;
int age;
};
int main() {
Dog a, b; // Dog型のオブジェクト(インスタンス)を2つ作成
a.name = "Pochi";
a.age = 3;
b.name = "Shiro";
b.age = 5;
cout << a.name << " は " << a.age << " 歳" << endl;
cout << b.name << " は " << b.age << " 歳" << endl;
return 0;
}Dog はクラス(型)であり、a や
b はそのオブジェクト(インスタンス)です。
メンバ関数は、クラスに定義された**機能(処理)**のことです。
そのオブジェクトに関する処理を行うときに使います。
// 10_member_function.cpp
#include <iostream>
using namespace std;
class Dog {
public:
string name;
int age;
void introduce() {
cout << name << " は " << age << " 歳の犬です。" << endl;
}
};
int main() {
Dog d; // Dog型のオブジェクト(インスタンス)
d.name = "Pochi";
d.age = 4;
d.introduce();
return 0;
}d は Dog
クラスのオブジェクト(インスタンス)であり、introduce()
はそのメンバ関数です。
次のコードを実行すると何が表示されますか?
// 10_pet_intro.cpp
#include <iostream>
using namespace std;
class Pet {
public:
string name;
void greet() {
cout << name << " です。よろしく!" << endl;
}
};
int main() {
Pet p; // Petクラスのオブジェクト(インスタンス)
p.name = "Tama";
p.greet();
return 0;
}Tama です。よろしく!
次の要件を満たすクラスを作成しなさい。
x, yshow() — 「(x, y)」の形式で表示するmain関数内で Point
クラスのインスタンスを生成し、適切な値を代入した上で show()
を呼び出すこと。
// 10_point_display.cpp
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
void show() {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p; // Pointクラスのオブジェクト(インスタンス)
p.x = 3;
p.y = 5;
p.show();
return 0;
}次の要件を満たすクラスを作成しなさい。
width, heightarea() — 面積を返すmain関数内で Rectangle
クラスのインスタンスを生成し、幅と高さに任意の値を代入し、area()
を呼び出して結果を表示すること。
// 10_rectangle_area.cpp
#include <iostream>
using namespace std;
class Rectangle {
public:
int width, height;
int area() {
return width * height;
}
};
int main() {
Rectangle r; // Rectangleクラスのインスタンス
r.width = 6;
r.height = 4;
cout << "面積: " << r.area() << endl;
return 0;
}次の要件を満たす Student クラスを作成しなさい。
name, scoreshow() — 「〇〇さんの点数は△点です」と表示するisPassed() — 60点以上なら true を返すmain関数内で Student
クラスのインスタンスを生成し、名前と点数を代入した上で
show() および isPassed()
を利用して出力を行うこと。
// 10_student_info.cpp
#include <iostream>
using namespace std;
class Student {
public:
string name;
int score;
void show() {
cout << name << " さんの点数は " << score << " 点です。" << endl;
}
bool isPassed() {
return score >= 60;
}
};
int main() {
Student s; // Studentクラスのオブジェクト(インスタンス)
s.name = "Yuki";
s.score = 75;
s.show();
if (s.isPassed()) {
cout << "合格です!" << endl;
} else {
cout << "不合格です…" << endl;
}
return 0;
}クラスは設計図であり、そこから作られる各変数は「オブジェクト」や「インスタンス」と呼ばれます。 どちらも同じ意味で使われることが多く、実際に使う場面では区別なく扱われます。