3-1-1. メンバ関数
公開日: 17:07 3. オブジェクト指向編/3-1. クラスとオブジェクト/3-1-1. メンバ関数
クラスのメンバ関数は変数などのように、その定義やプロトタイプをクラス定義内に持つ関数です。メンバとなっているクラスのオブジェクト上で動作し、そのオブジェクトのクラスのすべてのメンバへアクセスできます。
以前に定義したクラスを使って、直接アクセスする代わりにメンバ関数を使ってメンバへアクセスしてみましょう。
class Box { public: double length; // 箱の縦幅 double breadth; // 箱の横幅 double height; // 箱の深さ double getVolume(void);// 箱の体積を返す };
メンバ関数はクラス定義内か別個にスコープ解決演算子(::)を使って定義されます。メンバ関数をクラス定義内で定義するとinline指定子を使っていなくても関数はインラインで宣言されます。どちらにしてもVolume()関数は次のように宣言できます。
class Box { public: double length; // 箱の縦幅 double breadth; // 箱の横幅 double height; // 箱の深さ double getVolume(void) { return length * breadth * height; } };スコープ解決演算子を使い、クラスの外で同様の関数を定義したいのであれば次のようになります。
double Box::getVolume(void) { return length * breadth * height; }
ここでの重要な点は::演算子の前にクラス名をつけなければならないことです。あるオブジェクトのみに関係するデータを操作するときにメンバ関数はドット演算子(.)をつけて呼ばれます。
Box myBox; // オブジェクトの生成 myBox.getVolume(); // オブジェクトからメンバ関数を呼び出す
上のコンセプトを取り入れてクラス内の異なるメンバの値を取得してみましょう。
#include <iostream> using namespace std; class Box { public: double length; // 箱の縦幅 double breadth; // 箱の横幅 double height; // 箱の深さ // メンバ関数の宣言 double getVolume(void); void setLength( double len ); void setBreadth( double bre ); void setHeight( double hei ); }; // メンバ関数の定義 double Box::getVolume(void) { return length * breadth * height; } void Box::setLength( double len ) { length = len; } void Box::setBreadth( double bre ) { breadth = bre; } void Box::setHeight( double hei ) { height = hei; } // main() int main() { Box Box1; // Box型のBox1を宣言 Box Box2; // Box型のBox2を宣言 double volume = 0.0; // boxの体積を保存 // box 1の仕様 Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2の仕様 Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // box 1の体積 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // box 2の体積 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; return 0; }上のコードをコンパイルし実行すると、次の結果が得られます。
Volume of Box1 : 210
Volume of Box2 : 1560
0 件のコメント :
コメントを投稿