我是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的左侧必须具有class/struct/union。”
函数的第3行中的“record”用红色下划线表示错误。

我在这里迷路了。我尝试使用非常完整的作用域名称和其他所有名称,但它始终给出相同的错误。我不确定发生了什么,错误似乎非常...模糊。

最佳答案

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

但是,最好将student_name更改为std::string,然后您不必担心所有char复制。

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

10-12 00:12
查看更多