c++ - 我如何在单独的头文件中的结构中定义一个 char* 数组?

标签 c++ pointers struct header-files

我刚开始学习结构并将内容分成不同的文件。

目前我有一个像这样的 Main.cpp 文件:

#include <iostream>
    #include "StudentAnswerSheet.hpp"
using std::cout;
using std::endl;

int main(){

    StudentAnswerSheet sheet = {
        "Sally",
        {'a', 'b', 'a', 'd', 'c'}
    };

    cout << sheet.studentName << ":" <<endl;
    for(int i = 0; i <5; i++){
    cout << sheet.studentAnswers[i] << " " ;
    }
    return 0;
}

和一个单独的头文件,其中包含我的 StudentAnswerSheet 数据类型:

#include <string>
using std::string;

struct StudentAnswerSheet{
    string studentName;
    char studentAnswers[5];
};

理想情况下,我希望能够有最多 5 个字符的数组 来保存学生的答案。我想我可能需要从 char 更改为 char* 以获得一定程度的灵 active ,但是当我尝试实现它时,我收到一条错误消息“char [0] 的初始化程序太多”并且不确定如何更改工作表初始化.

如果我切换到一个 char* 数组,我也不确定跟踪我的数组包含多少元素的最佳方法是什么。如果我用 cin 接收学生的答案,那么我可以跟踪答案的数量最多为 5,但如果我只是想自己初始化答案,就像我现在进行测试一样,我不确定计算 studentAnswers 大小的最有效方法是什么,所以对此的任何建议都是也非常感谢。

感谢您的帮助!

最佳答案

因为您似乎可以使用 std::string , 那你为什么不使用 std::vector<char>而不是使用 char[5]或者考虑使用 char*为了灵 active ?在你的情况下,你可以简单地使用 std::string然后将其中的每个字符解释为学生答案

此外,由于 StudentAnswerSheet不是 POD,这意味着以下会产生编译错误,除非您使用 C++11:

//error in C++98, and C++03; ok in C++11
StudentAnswerSheet sheet = {
    "Sally",
    {'a', 'b', 'a', 'd', 'c'}
};

这是我会做的:

struct StudentAnswerSheet
{
    std::string studentName;
    std::string studentAnswers;

    //constructor helps easy-initialization of object!
    StudentAnswerSheet(const std::string & name, const std::string & answers) 
                : studentName(name), studentAnswers(answers) {}
              //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
};            // it is called member-initialization list

然后将其用作:

StudentAnswerSheet sheet("Sally", "abadc");//easy: thanks to the ctor!

std::cout << sheet.studentName << std::endl;
for(size_t i = 0; i < sheet.studentAnswers.size(); ++i)
{
     std::cout << sheet.studentAnswers[i] << " " ;
}

关于c++ - 我如何在单独的头文件中的结构中定义一个 char* 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8325767/

相关文章:

c++ - 如何在 `QQmlApplicationEngine` 派生类中访问 `QQuickItem` 的对象?

c++ - 需要左值作为左操作数赋值时

c++ - 为什么存在奇特的指针?

释放后检查结构体是否释放

c - 将数组发送到函数仅发送数组的第一个元素

c# - OutOfMemoryException 使用计时器已用事件 c#

c++ - 对的任何替代方案?

c++ - wxWidgets,wxListCtrl : How to prevent auto size of column when db-click on divider

你能改变 C 非指针类型的内存地址吗?

c++ - 错误 : 'object' was not declared in this scope (C++)