初学C++结构体,只是定义了一个结构体加一个变量,就出现了警告。
代码如下,vs2019把警告线划在了定义完结构体之后的大括号上。
#include<iostream>
using namespace std;
struct student {
// 姓名
string name;
// 年龄
int years;
//分数
int score;
};
int main()
{
truct student s3 = { "李三",19,660 };
cout << "name=" << s3.name << endl << "years=" << s3.years << endl << "score=" << s3.score << endl;
system("pause");
return 0;
}
警告内容是
警告 C26495 未初始化变量 student::years。始终初始化成员变量(type.6)。
警告 C26495 未初始化变量 student::score。始终初始化成员变量(type.6)。
有什么办法可以解决这两个警告吗?
加上构造就行了
struct student {
student(string n="",int y=0,int s=0):
name(n),years(y),score(s)
{}
// 姓名
string name;
// 年龄
int years;
//分数
int score;
};
注:c++中结构体和类除了默认访问权限,其他类能做到的,struct也能,基本上是一样的,只是平时使用时习惯使用struct来表达纯数据无方法的结构。
如果你给的代码是完整无误的,那么只有一个错误就是truct student s3改为struct student s3 或者student s3