简体   繁体   中英

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 ?

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.

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. Make a destructor to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM