结构上的一些问题

Some problems with struct

本文关键字:问题 结构上      更新时间:2023-10-16
#include <iostream>
using namespace std;
struct student{
    char name[10];
    int  grade;
};

int main() {
    struct student s[10];
    student s[0].name = "Jack";
    cout<<s[0].name;
}

我想创建结构类型数据student作为数组。但是当我这样做的时候,出现了一些错误,我不知道为什么。以下是错误:

1。错误:用不同的类型重新定义's': 'student[0]'与'struct student [10]'

    student s[0].name = "Jack";
            ^

2。注:前面的定义在这里

 struct student s[10];
                ^

3。错误:声明结束

 student s[0].name = "Jack";
                ^
                ;
  1. char name[10];:
    1. 10字符对于名称来说太短。
    2. char假定名称不在ASCII或UTF-8之外,并且看起来不像您正在使用Unicode库。
    3. 用于存储字符串的固定大小数组不符合c++的习惯。
    4. 解决方案:使用std::stringstd::wstring -并使用Unicode库!
  2. struct student s[10]
    1. 这不是惯用的c++。不需要使用struct关键字。只要student s[10];就足够了。
    2. 同样,避免固定大小的数组,除非您确定将使用10条记录。使用std::vector<student>代替。
  3. 你没有初始化数组,所以数据成员将包含未定义/未初始化的数据。使用= {0}来清空内存和/或定义student构造函数。
  • student s[0].name = "Jack";
    1. 无法编译。我想你的意思是把s[0].name = "Jack"
    2. 没有为字符串定义赋值操作符=(默认情况下)。请注意,您的结构体的成员类型是char,而字符串字量是const char[N],因此实际上您将指针(由于数组衰减)分配给char成员。这个操作没有意义。
  • 你的main没有返回值。成功时使用return EXIT_SUCCESS;。这不是严格要求的,但我个人认为显式返回一个值是很好的实践。