LoginSignup
0
0

More than 3 years have passed since last update.

C++における構造体のコンストラクターを用いた初期化

Posted at

はじめに

この題についてネット上で容易に情報を見つけることができなかったので、ここに記述します。
参考文献:C++によるプログラミングの原則と実践 page 299

本題

次のような構造体を定義したとする。

struct Account { // 銀行口座
    std::string name; // 名義
    int balance; // 残高

    Account(std::string n, int b) {} //コンストラクター
};

次のような初期化は動作する。

Account stroustrup {"Bjane", 19501230};
Account ezoe = {"Ryo", 44290};
Account takahasi = Account{"Naohiro", 4205000};
Account yokoyama("Kouki", 60); //C++98の古いスタイル

次のような初期化は失敗する。

Account Kazimierz;

コード全体を次に記述する。

#include <string>

struct Account { 
    std::string name; 
    int balance;

    Account(std::string n, int b) {} 
};

int main() {
    Account stroustrup {"Bjane", 19501230}; //ok
    Account ezoe = {"Ryo", 44290}; //ok
    Account takahasi = Account{"Naohiro", 4205000}; //ok
    Account yokoyama("Kouki", 60); //ok

    Account Kazimierz; //エラー
}
0
0
1

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
0
0