如何在c ++中使用strcopy

soa*_*yek 1 c++ copy char

在c ++中,我有一个名为"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 !
        strcopy(this.stMajor, stMajor);
        this.stAverage = stAverage;
    }
Run Code Online (Sandbox Code Playgroud)

我该怎么办 ?!

Pra*_*rav 7

this是C++中的指针,而不是Java中的引用.再加上你需要的strcpy()不是strcopy()

试试这个

    strcpy(this->stName, stName); 
    strcpy(this->stMajor, stMajor);
Run Code Online (Sandbox Code Playgroud)

PS:在C++中,总是建议选择std::string超过C风格的数组

更简洁的代码版本就是这样的

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;          
    }
};
Run Code Online (Sandbox Code Playgroud)