此指针错误没有构造函数的实例与参数列表匹配

时间:2018-10-23 14:28:05

标签: c++ constructor this-pointer

请帮助错误:没有构造函数的实例与参数列表匹配。 并且还请帮助解释有关“ strcpy(this-> name,name);”

class Student {
    char name[50];
    char surname[50];
    int age;
public:
    Student(char name[], char surname[], int age) {
        strcpy(this->name, name); // please explain this line what does it means?
        strcpy(this->surname, surname);
        this->age = age;
    }
    void Show() {
        cout << "Name: " << this->name << endl;
        cout << "Surname: " << this->surname << endl;
        cout << "Age: " << this->age;
    }
};

int main() {
    Student A("Ivan", "Sidoroff", 25);
    A.Show();

    system("pause");
    return 0;
}

enter image description here

1 个答案:

答案 0 :(得分:2)

  

请帮助错误:没有构造函数的实例与参数匹配   列表。

代替此:

Student(char name[], char surname[], int age) {

尝试一下:

Student(const char *name, const char *surname, int age) {

它抱怨是因为char指针与const char的指针不匹配。

  

strcpy(this->name, name); //请解释这一行的作用   是什么意思?

它将字符串从name(传递的参数)复制到另一个name(是class Student的一部分)。由于两者都称为name,因此不明确。在这种情况下,name引用参数,而this->name用于引用class Student中的字段。

通常,this是指向调用该函数的对象的指针。