【C++】C++中will be initialized after [-Wreorder]

00. 目录

在这里插入图片描述

01. 问题描述

编译C++代码的时候出现will be initialized after [-Wreorder]警告。

deng@local:~/code/2c++$ g++ 7class.cpp  -Wall
7class.cpp: In constructor ‘Time::Time(int, int, int)’:
7class.cpp:37:9: warning: ‘Time::mM’ will be initialized after [-Wreorder]
   37 |     int mM;
      |         ^~
7class.cpp:34:9: warning:   ‘int Time::mH’ [-Wreorder]
   34 |     int mH;
      |         ^~
7class.cpp:15:5: warning:   when initialized here [-Wreorder]
   15 |     Time(int h, int m, int s): mM(m), mH(h), mS(s)
      |     ^~~~
deng@local:~/code/2c++$


02. 问题分析

构造函数时,初始化成员变量的顺序要与类声明中的变量顺序相对应,若不对应,则出现如题错误。

参考:gcc warning" ‘will be initialized after’

03. 问题解决

解决方法就是按照顺序进行初始化。

04. 问题验证

错误之前的代码:

#include <iostream>

using namespace std;


//时间类
class Time
{
public:
    Time()
    {
        cout << "Time 无参构造" << endl;
    }

    Time(int h, int m, int s): mM(m), mH(h), mS(s)
    {

        cout << "Time 有参构造函数" << endl;
    }

    ~Time()
    {
        cout << "Time 析构" << endl;
    }

    void showTime(void)
    {
        cout << mH << ":" << mM << ":" << mS << endl;
    }


private:
    //时
    int mH;

    //分
    int mM;

    //秒
    int mS;
};


int main(void)
{

    Time t1(2023, 8, 9);
    t1.showTime();

    return 0;
}

修改之后的代码:


#include <iostream>

using namespace std;


//时间类
class Time
{
public:
    Time()
    {
        cout << "Time 无参构造" << endl;
    }

    Time(int h, int m, int s): mH(h), mM(m), mS(s)
    {

        cout << "Time 有参构造函数" << endl;
    }

    ~Time()
    {
        cout << "Time 析构" << endl;
    }

    void showTime(void)
    {
        cout << mH << ":" << mM << ":" << mS << endl;
    }


private:
    //时
    int mH;

    //分
    int mM;

    //秒
    int mS;
};


int main(void)
{

    Time t1(2023, 8, 9);
    t1.showTime();

    return 0;
}

05. 附录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沧海一笑-dj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值