Menu
Coddy logo textTech

外部ファイル

CoddyのC++ジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 1/104。

C++では、コードは複数のファイルに分割され、#includeディレクティブを使用して接続されます。

別のファイル MyClass.h

#include <string>

class MyClass {
public:
    std::string greet() {
        return "Hello from MyClass!";
    }
};

メインファイルにインクルードして使用します

#include <iostream>
#include "MyClass.h"

int main() {
    MyClass obj;
    std::cout << obj.greet() << std::endl;
    return 0;
}

出力:

Hello from MyClass!

自作のファイルにはダブルクォーテーション "" を使用し、システムやライブラリのヘッダーにはアングルブラケット <> を使用します。#include ディレクティブは、コンパイル前にファイルの内容をソースコードにコピーします。

challenge icon

チャレンジ

簡単

main.cppMyClass.h ヘッダーファイルをインクルードし、MyClass オブジェクトを作成して、greet() を呼び出した結果を出力してください。

出力形式: Greeting: <result>

チートシート

C++では、コードは複数のファイルに分割され、#includeディレクティブを使用して接続されます。

システム/ライブラリのヘッダーには山括弧 <> を使用します:

#include <iostream>
#include <string>

自作のヘッダーファイルにはダブルクォーテーション "" を使用します:

#include "MyClass.h"

ヘッダーファイルの例 MyClass.h

#include <string>

class MyClass {
public:
    std::string greet() {
        return "Hello from MyClass!";
    }
};

main.cpp でヘッダーを使用する:

#include <iostream>
#include "MyClass.h"

int main() {
    MyClass obj;
    std::cout << obj.greet() << std::endl;
    return 0;
}

自分で試してみよう

#include <iostream>
#include <string>
// TODO: MyClassヘッダーファイルをインクルードする

int main() {
    std::string testCase;
    std::getline(std::cin, testCase);
    
    // TODO: MyClassオブジェクトを作成し、greet()を呼び出す
    
    std::cout << "Test completed" << std::endl;
    return 0;
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン