2010-12-12 58 views
1

在C++中使用strcopy,我有一个名为 “Student.h”如何在C++

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; 
    } 

文件,我应该怎么办?!

+3

'strcopy()'? '的strcpy()'? – 2010-12-12 16:14:21

回答

7

this是在C++中的指针,而不是如参考在Java中。另外,您需要的是strcpy()strcopy()

试试这个

strcpy(this->stName, stName); 
    strcpy(this->stMajor, stMajor); 

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;   
    } 
}; 
+0

@Prasoon:请不要让人们通过值来传递'std :: string',就像你当前的std :: string stMajor'一样。请使'std :: string const&stMajor'。坏习惯很难摆脱,最好从好习惯开始:-) – 2010-12-12 16:26:15

+0

这是一个C++的作业,我没有时间学习 – 2010-12-12 16:30:22

+1

@soad:你放下学习C++的工作,而你没有学习的时间?好吧,那你就搞砸了。 – 2010-12-12 16:32:22

0

this是一个指针,而不是一个参考,所以你必须使用指针引用运营商:

strcpy(this->stName, stName); 

strcpy((*this).stName, stName); 

而且,我不推荐使用char[20]作为一个数据类型学生姓名 - 这很容易发生缓冲区溢出错误。您可以通过使用strncpy

strcpy(this->stName, stName, 19); 
    this->stName[20]=0; 

但最方便的方法是使用std::string,可以通过转让方便地复制克服这一点。最后,如果您为成员变量名称选择了一些约定,则可以在不使用this的情况下引用它们。例如:

class Student { 
public: 

    std::string m_stName; 

... 
    Student(int stId, std::string stName, ...) { 
     m_stName=stName; 

或甚至(使用初始化):

Student(int stId, std::string stName, ...) : m_stName(stName) { 
    m_stName=stName; 
1

我认为你的意思是strcpy函数(没有)。

0

您不能使用std::string

string s1, s2 = "example"; 
s1 = s2; 

无论如何,问题是,在C++ this返回指针,因此this.stId是错误的,正确的形式将是this->stId,或者可替换地(*this).stId

2

我该怎么办?

您应该:

  • 使用std::string,而不是原始数组。

  • 使用std::list而不是发明自己的(除了学习链接列表的目的)。

  • 没有指出正式参数中的数组大小,比如你的char stName [20];正式参数类型不保留大小信息,它只是指向一个指针类型。

  • 一般避免直接使用this

  • 通常在构造函数体中使用初始化列表而不是赋值。

干杯&心连心,