• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

cppのclass

date: 2022-07-02 excerpt: cppのclassの使い方

tag: c++cppclass


cppの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;
}


c++cppclass Share Tweet