C++ struct结构体初始化

c++ 中可以将结构体看作没有任何成员函数的对象,因此也可以使用构造函数进行初始化。

#include <bits/stdc++.h>
using namespace std;
struct Date
{
    int year;
    double month;
    string day;
    int a[10];
    Date()
    {
        year = 2022;
        month = 7.0;
        day = "22";
    }
    Date(int year) //这里可以使用 Date(int year=0) 来指定year默认值,但是这样就不能有Date()
    {
        this->year = year;
        month = 7.0;
        day = "22";
    }
};

int main()
{
    // 默认值初始化
    Date date1;
    cout<<date1.year<<" "<<date1.month<<" "<<date1.day<<" "<<date1.a[0]<<endl; // 2022 7 22 0

    // 指定一个值
    Date date2(2022);
    cout<<date2.year<<" "<<date2.month<<" "<<date2.day<<" "<<date2.a[0]<<endl; // 2022 7 22 0
    return 0;
}

C++结构体初始化方法_hhhcbw的博客-CSDN博客_c++结构体初始化在C++里可以将结构体看作没有任何成员函数的对象,下面对C++结构体的几种初始化方法进行总结。https://blog.csdn.net/weixin_44491423/article/details/125938286

猜你喜欢

转载自blog.csdn.net/u013288190/article/details/127013881