[英]Pass char array to parameterized constructor
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);
}
Help me to understand where is my fault? 帮助我了解我的错在哪里? I think i've a lack 'bout pointer :( How to assign n[20] array to *genre member of class ? 我认为我缺少一个回合指针:(如何将n [20]数组分配给* genre类的成员?
A constructor can only be invoked at the time of the declaration of an object. 构造函数只能在声明对象时调用。 Your constructor looks alright, but the code in main
is not. 您的构造函数看起来不错,但main
的代码却不正确。
int main() {
char n[20];
cin >> n;
books harrypotter(n); // calling parameterized constructor
cout << harrypotter.genre; // == cout << n;
}
Also, do keep in mind that any memory allocated using new
will not be freed until you explicitly do so. 另外,请记住,使用new
分配的任何内存都不会被释放,除非您明确地这样做。 Make a destructor to do that. 使一个析构函数可以做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.