我是 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/