LoginSignup
8
8

More than 5 years have passed since last update.

#C/C++初心者≠プログラマ初心者用 基礎知識チートシート#2

Posted at

クラス

コンストラクタとデストラクタ

  • 多分他の言語よりも重要になってくるっぽい気がする。変数の初期化が必須だし、GCもないので。

example:

classexam
#include <iostream>

#include <iostream>

class CTest
{
public:
    int health;
    int mana;

    CTest(int hp, int mp); // コンストラクタ
    ~CTest(); // デストラクタ
};

CTest::CTest(int hp, int mp)
{
    health = hp;
    mana = mp;
}

CTest::~CTest() // デストラクタは引数も戻り値も持たない
{
    std::cout << "デストラクタがよばれたよ!" << std::endl;
}


int main()
{
    CTest t(100, 20);
    std::cout << t.health << "\n" << t.mana << std::endl;
    return 0;
}
// デストラクタ => healthとmanaが出力 => デストラクタの順で呼ばれる

こんな感じ。
  

newとdelete

  • C++におけるnewとdeleteは、VBやなんかとは(多分、見かけ上は)違った意味を持つようだ

 先の例に示したように、newを使わなくてもインスタンスの生成は行えるし、deleteしなくてもデストラクタの呼び出しは行われる。
 newとdeleteの働きはCでいうmallocとfreeと似ていて、メモリの動的確保と解放を行えるようだ。ただし、mallocとfreeは関数であり、newとdeleteは演算子であることに注意する。
 次に簡単な例を示す:

プリミティブへのnew/delete
#include <iostream>

int main()
{
    int *p;

    p = new int(); // int型の領域を確保.また、ここでコンストラクタの呼び出しも行われる。
    *p = 42;
    std::cout << *p << std::endl;

    delete p;
    return 0;
}

 newでコンストラクタが呼ばれるのと同じように、deleteではデストラクタが呼ばれる。C++にはintのようなプリミティブにもコンストラクタがある。
 配列の初期化についてはまた記法が異なるので、書くときに調べよう。

 上記のように、newとdeleteで指定されるのはポインタだ。

 クラスに対しても、次のように使える:

クラスへのnew/delete
#include <iostream>

int main()
{
    CExample* p;

    p = new CExample(100);
    std::cout << p->getNum() << std::endl;
    delete p;
    return 0;
}



  
  

インスタンス生成の色々もまたちょっと趣が違いそうなので、次でまとめる。

8
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8