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;
}