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] 数组分配给类的 *genre 成员?
最佳答案
构造函数只能在对象声明时调用。您的构造函数看起来不错,但 main
中的代码却不行。
int main() {
char n[20];
cin >> n;
books harrypotter(n); // calling parameterized constructor
cout << harrypotter.genre; // == cout << n;
}
另外,请记住,使用 new
分配的任何内存都不会被释放,除非您明确这样做。制作一个析构函数来做到这一点。
关于c++ - 将 char 数组传递给参数化构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36373710/