Cplusplus-cpp-class-member-functions

提供:Dev Guides
移動先:案内検索

C ++クラスメンバー関数

クラスのメンバー関数は、他の変数と同様に、クラス定義内にその定義またはプロトタイプを持つ関数です。 メンバーであるクラスのオブジェクトを操作し、そのオブジェクトのクラスのすべてのメンバーにアクセスできます。

以前に定義したクラスを直接アクセスする代わりに、メンバー関数を使用してクラスのメンバーにアクセスします-

class Box {
   public:
      double length;        //Length of a box
      double breadth;       //Breadth of a box
      double height;        //Height of a box
      double getVolume(void);//Returns box volume
};

メンバー関数は、クラス定義内で定義するか、* scope resolution operator、-を使用して個別に定義できます。 クラス定義内でメンバー関数を定義すると、インライン指定子を使用しなくても、関数 *inline が宣言されます。 したがって、以下のように* Volume()*関数を定義できます-

class Box {
   public:
      double length;     //Length of a box
      double breadth;    //Breadth of a box
      double height;     //Height of a box

      double getVolume(void) {
         return length *breadth* height;
      }
};

必要に応じて、次のように scope resolution operator (::)を使用して、クラス外で同じ関数を定義できます-

double Box::getVolume(void) {
   return length *breadth* height;
}

ここで重要な点は、::演算子の直前にクラス名を使用する必要があることだけです。 メンバー関数は、次のようにそのオブジェクトに関連するデータを操作するオブジェクトでドット演算子()を使用して呼び出されます-

Box myBox;         //Create an object

myBox.getVolume(); //Call member function for the object

クラス内の異なるクラスメンバーの値を設定および取得するための上記の概念を入れてみましょう-

#include <iostream>

using namespace std;

class Box {
   public:
      double length;        //Length of a box
      double breadth;       //Breadth of a box
      double height;        //Height of a box

     //Member functions declaration
      double getVolume(void);
      void setLength( double len );
      void setBreadth( double bre );
      void setHeight( double hei );
};

//Member functions definitions
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 function for the program
int main() {
   Box Box1;               //Declare Box1 of type Box
   Box Box2;               //Declare Box2 of type Box
   double volume = 0.0;    //Store the volume of a box here

  //box 1 specification
   Box1.setLength(6.0);
   Box1.setBreadth(7.0);
   Box1.setHeight(5.0);

  //box 2 specification
   Box2.setLength(12.0);
   Box2.setBreadth(13.0);
   Box2.setHeight(10.0);

  //volume of box 1
   volume = Box1.getVolume();
   cout << "Volume of Box1 : " << volume <<endl;

  //volume of box 2
   volume = Box2.getVolume();
   cout << "Volume of Box2 : " << volume <<endl;
   return 0;
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Volume of Box1 : 210
Volume of Box2 : 1560