how to use strcopy in c++
in c++ , i have a file named "Student.h"
class LinkedList {
private:
class Student {
public:
int stId;
char stName [20];
char stMajor[20];
double stAverage;
Student * next;
Student() {
next = 0;
}
Student(int stId, char stName [20], char stMajor[20], double stAverage) {
this.stId = stId;
strcopy(this.stName, stName); // there is error here !
开发者_StackOverflow strcopy(this.stMajor, stMajor);
this.stAverage = stAverage;
}
what should i do ?!
this
is a pointer in C++, not a reference as in Java. Plus what you need is strcpy()
not strcopy()
Try this
strcpy(this->stName, stName);
strcpy(this->stMajor, stMajor);
P.S : In C++ it is always recommended to prefer std::string
over C-style arrays
A much cleaner version of your code would be something like this
struct Student {
int stId;
std::string stName;
std::string stMajor;
double stAverage;
Student * next;
Student():stId(),stAverage(),next()//prefer initialization-list to assignment
{
}
Student(int stId, const std::string &stName, const std::string &stMajor, double stAverage){
this->stId = stId,
this->stName = stName ,
this->stMajor = stMajor,
this->stAverage = stAverage;
}
};
what should i do ?!
You should:
use
std::string
instead of raw arrays.use
std::list
instead of inventing your own (except for purpose of learning about linked lists).not indicate array sizes in formal arguments, like your
char stName [20]
; the formal argument type does not retain the size information, it just devolves to a pointer type.generally avoid using
this
directly.generally use initializer lists instead of assignments in the constructor body.
Cheers & hth.,
I think you mean the strcpy
function (without o).
Can you not use std::string
?
string s1, s2 = "example";
s1 = s2;
Anyway, the problem is that in C++ this
returns a pointer, therefore this.stId
is wrong, the correct form would be this->stId
, or alternatively (*this).stId
.
this
is a pointer, not a reference, so you have to use pointer dereferencing operators:
strcpy(this->stName, stName);
or
strcpy((*this).stName, stName);
Moreover, I don't recommend using char[20]
as a datatype for student names - that is very prone to buffer overflow errors. You could overcome this by using strncpy
strcpy(this->stName, stName, 19);
this->stName[20]=0;
But the most convenient way is using std::string
, which can be conveniently copied by assignment.
And last, if you chose some convention for member variable names, you could just refer to them without this
. Eg:
class Student {
public:
std::string m_stName;
...
Student(int stId, std::string stName, ...) {
m_stName=stName;
or even (using initializers):
Student(int stId, std::string stName, ...) : m_stName(stName) {
m_stName=stName;
精彩评论