c++ - 在 C++ 中对来自全局函数的结构成员使用方法

标签 c++ function struct compiler-errors c-str

我是 C++ 的新手,总是会遇到一些小问题。最近的似乎是结构的问题。

struct student_record{
student_record(std::string name, int ident, double gpa){
    for (int i = 0; i < name.length(); i++){
        student_name[i] = name[i];
        student_name[i + 1] = NULL;
    }

    student_ident = ident;
    student_gpa = gpa;
}
//constructor to initialize student_record

static const unsigned int MAX_NAME_LENGTH = 21;
char student_name[MAX_NAME_LENGTH];
int student_ident = 1234;
double student_gpa = 4.0;
};

我想用我的函数“print_student”打印出这个学生的名字

void print_student(const student_record record){
std::cout << "Student name: ";
std::cout << record.student_name.c_str();
std::cout << std::endl;

std::cout << "  Student ID: " << record.student_ident << std::endl;
std::cout << "         GPA: " << record.student_gpa << std::endl;
}

我收到错误“Intellisense:表达式必须具有类类型” 编译器错误说“.c_str 的左边必须有类/结构/union ”。 “record”在函数的第 3 行中带有红色下划线并给出了错误。

我迷路了。我尝试使用非常完整的范围名称和所有内容,但它一直给出相同的错误。我不确定发生了什么,错误似乎非常……模糊。

最佳答案

c_str 方法用于std::string 对象。你的 student_name 是一个字符数组,所以你不需要 .c_str() 最后。

但是,您最好将 student_name 更改为 std::string,这样您就不必担心所有的字符复制。

关于c++ - 在 C++ 中对来自全局函数的结构成员使用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30690490/

相关文章:

c++ - C++-候选函数不可行: no known conversion from 'struct ' to 'struct (&)'

c++ - 是否可以将每个 if-else 结构替换为等效的条件表达式?

c++ - 从 tcp 读取 float

Scala函数: What is the return type

c - 函数参数中的 "int (*)[]"是否衰减为 "int **"?

c - 用 C 语言编写一个程序,使用 rand() 函数创建 1000 个结构体

c++ - "name::name"在 C++ 中意味着什么?

c++ - 如何从 GDI 设备上下文中获取 32bpp 位图/图像?

excel - 带有 IF 的 VBA Excel 中的函数

.net - 当结构体实例的属性为 'Reference Type?' 时会发生什么