struct のコンストラクタを使ってみる (C++)
C++
Published: 2020-07-06

確認環境

$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

調査

test.cpp

#include <bits/stdc++.h>
using namespace std;

struct person {
    string name;
    int age;

    // コンストラクタを定義
    person(string name, int age): name(name), age(age) {};
};

int main() {
    person p("person name", 20);
    cout << p.name << endl;
    cout << p.age << endl;
}

出力結果

person name
20