简体   繁体   中英

getting error on compiling small C++ program

when i compile the program i get an error about int when i create a bookClass object using the 2 argument constructor. the error has somerthing to do with the integer argument parsed to the constructor. the program is:

 #include <iostream>
 #include <string>

 using namespace std;

  class bookClass{
  private:
  string bookName;
  int bookNumber;



  public:


     void setName(string c){
    bookName=c;
    }

    void setNumber(int d){
    bookNumber=d;
    }

    string getName(){
    return bookName;
    }

    int getNumber(){
    return bookNumber;
    }
   bookClass(string a, int b){
    bookName=a;
   bookNumber=b;
    }


   };

  int main()
  {
   int numberr;
   string name;
    cout << "Enter the book name:   ";
    cin >> name;
    cout << "\nEnter the book number:  ";
    cin >> numberr;

    bookClass book=new bookClass(name, numberr);

     cout << "\n\nThe book " << book.getName() << " has book number " <<        
      book.getNumber() << endl;


    return 0;
    }

Compiling your code I didn't get the error you suggested. However, there is an issue with this line:

bookClass book = new bookClass(name, numberr);

C++ is not Java. new returns a pointer to memory dynamically allocated for the given class.

What you want is just:

bookClass book (name, numberr);

The problem with your code is simple. I suppose you were programming in Java or C# before C++. In C++ we call new operator only if we want to create an object explicitely on heap (and get a pointer to it).

bookClass* book=new bookClass(name, numberr);

However, now you are in troubles because you are calling book.getName() where book is of type pointer to something and it has no member getName() . You have to first dereference that pointer and then call a member function (*book).getName(); or simply book->getName(); .

However, since C++'s objects do not have to be on the heap (Java objects have to) you can create an object without new operator using bookClass book(name, numberr);

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