cppのclass

cppのclassの使い方

タグ class


概要

  • 組織立てた開発用のheaderにインターフェースを記す方法と、簡易的に一つのファイルにすべてを記す方法がある
    • mockなどを利用する際にはheaderに実装が書かれているとまずいことがある
  • デフォルトではメンバ変数や関数はprivateとなる

headerfileと分離する方法

  • ~.hppというファイルにインターフェースを記す
  • ~.cppに対応する実装を記す

ヘッダーファイル

// インターフェースの定義
// 一般的にはheaderfileに記す
class Room {
public:
    double length;
    double breadth;
    double height;
    Room();
    double calculateArea();
    double calculateVolume();
};

実装ファイル

#include <iostream>
#include "tc2.hpp"
using namespace std;

// 実装
// インスタンスを明示化するには`this`を記す
Room::Room(){
}
double Room::calculateArea() {
    return this->length * this->breadth;
}
double Room::calculateVolume() {
    return this->length * this->breadth * this->height;
}

int main() {
    Room room1;
    room1.length = 42.5;
    room1.breadth = 30.8;
    room1.height = 19.2;
    cout << "Area of Room =  " << room1.calculateArea() << endl;
    cout << "Volume of Room =  " << room1.calculateVolume() << endl;
}

実装ファイルにすべて記す方法

#include <iostream>
using namespace std;

class Room {
public:
    double length;
    double breadth;
    double height;
    Room() {
    }
    double calculateArea() {
        return length * breadth;
    }
    double calculateVolume() {
        return length * breadth * height;
    }
};

int main() {
    Room room1;
    room1.length = 42.5;
    room1.breadth = 30.8;
    room1.height = 19.2;
    cout << "Area of Room =  " << room1.calculateArea() << endl;
    cout << "Volume of Room =  " << room1.calculateVolume() << endl;
}