通过构造函数初始化char [40]

Yod*_*oda 0 c++ char

我想初始化对象属性,但它只是继续说类型不匹配.怎么纠正呢?

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;
class Student{
public:
    int nr_ID;
    char nazwisko[40];
    char imie[40];
    double punkty;
    Student* next;

    Student(int nr_ID, char nazwisko[40], char imie[], double punkty){
        this->nr_ID = nr_ID;
        this->nazwisko = nazwisko;//HERE
        this->imie = imie;//HERE
        this->punkty = punkty;
        next = NULL;
    }

    ~Student(){}

};
Run Code Online (Sandbox Code Playgroud)

Jos*_*eld 5

没有数组类型参数这样的东西.您声明的那个参数char nazwisko[40]实际上已转换为指针类型char* nazwisko.所以现在你可以看到你正在尝试分配一个指向数组的指针.当然那不行.

实际上,您根本无法简单地将数组分配给彼此.如果需要,您必须复制元素.您可以使用C函数strcpy来执行此操作,这将考虑参数应该是C样式的字符串.如果要复制完整数组,那么您可能希望使用std::copy.

如果您确实使用文本字符串,那么使用标准std::string类型执行此操作会更好.它们比以下数组更容易传递和分配char:

std::string nazwisko;
std::string imie;
// ...

Student(int nr_ID, std::string nazwisko, std::string imie, double punkty){
    this->nazwisko = nazwisko;
    this->imie = imie;
    // ...
}
Run Code Online (Sandbox Code Playgroud)

实际上,您可以省去默认初始化这些成员变量的痛苦,然后使用构造函数成员初始化列表分配给它们:

Student(int nr_ID, std::string nazwisko, std::string imie, double punkty)
  : nr_ID(nr_ID), nazwisko(nazwisko), imie(imie), punkty(punkty), next(NULL)
{ }
Run Code Online (Sandbox Code Playgroud)