将 char 数组传递给参数化构造函数

Pass char array to parameterized constructor

本文关键字:参数 构造函数 char 数组      更新时间:2023-10-16
class books{
public:
    char* genre;
    books(char *n);
};
books::books(char*n){
    genre = new char[strlen(n)+1];
    strcpy(genre,n);
}
int main(){
   book harrypotter;
   char n[20]; 
   cin>>n;
   harrypotter.books(n);
}

帮助我了解我的错在哪里?我想我缺少'回合指针:(如何将 n[20] 数组分配给类的 *流派成员?

构造

函数只能在声明对象时调用。您的构造函数看起来没问题,但main中的代码却不正常。

int main() {
   char n[20]; 
   cin >> n;
   books harrypotter(n);            // calling parameterized constructor
   cout << harrypotter.genre;      // == cout << n;     
}

此外,请记住,在显式执行此操作之前,不会释放使用 new 分配的任何内存。创建一个析构函数来做到这一点。