c++ - How to initialize an array in the member initializer list -
complete beginner in c++.
this member initialization list:
student.cpp
student::student(int studentid ,char studentname[40]) : id(studentid), name(studentname){}; student.h
class student{ protected: char name[40]; int id; } my problem name of type char[40], so, name(studentname) displays error of:
a value of type "char *" cannot used initialize entity of type "char [40]" how can initialize name array, studentname array in member initializer list? don't want use string, , have tried strcpy , didn't work
since can't initialize (raw) arrays other arrays or assign arrays in c++, have 2 possibilities:
the idiomatic c++ way use
std::string, , task becomes trivial:class student{ public: student(int studentid, const std::string& studentname) : id(studentid), name(studentname) {} protected: std::string name; int id; };then, when needed, can underlying raw
chararraynamecallingc_strmember function:const char* cstringname = name.c_str();if want use
chararray instead, things more complicated. can first default-initialize array , fill in constructor bodystrcpy:class student{ public: student(int studentid, const char* studentname) : id(studentid) { assert(strlen(studentname) < 40); // make sure given string fits in array strcpy(name, studentname); } protected: char name[40]; int id; };note argument
char* studentnameidenticalchar studentname[40], since can't pass arrays parameters value, why compiler treatschar*pointing firstcharin array.
Comments
Post a Comment