开发者

basic C++ question

开发者 https://www.devze.com 2022-12-12 22:07 出处:网络
I see in a class notices of a friend this: void show_results(Book& foreign_bo开发者_高级运维oks) {

I see in a class notices of a friend this:

    void show_results(Book& foreign_bo开发者_高级运维oks) {
       int total_books

       total_books = foreign_books.getBooksNumber();
       cout << total_books << endl;
    }

this is a good class definition?

   class Book{
      public:
      Book();

      int getBooksNumber();
   };

ps: i've writing this from mobile phone, and i cannot check too much documentation(I'm newbie too). I need your confirmation. ty


It's really hard to tell what you are asking. Let me offer some criticisms, though. Maybe these will help.

The show_results method should be const-correct. That means you should pass foreign_books as a const:

const Book& foreign_books

This way, your compiler will complain if you try to modify foreign_books at all in your method.

As mgb points out, your Books class won't work because the show_results method requires a Book, not a Books. But once you fix that, you probably want to make the getBooksNumber const-correct as well:

int getBooksNumber() const;

You haven't told us what you are trying to accomplish here, so it's really hard to tell if you are close to correct in what you are doing.

Finally, you missed a semicolon in your show_results method:

void show_results(Book& foreign_books) {
   int total_books; // **here**

   total_books = foreign_books.getBooksNumber();
   cout << total_books << endl;
}


Except that Books and Book isn't the same (typ0)

And you have to have some data member in Books to store the number, and some way of generating it.
You probably also need some sort of factory to create a unique number for each Books()


I am not sure if you are trying to associate a unique number to each book or just if you are keeping track of total number of Book objects constructed so far. If former is the case then you should declare a member variable saying bookNumber in Book class, and in getBooksNumber() you should return the value assigned to the bookNumber variable. Better if you make getBooksNumber() as constant function and if you invoke this function with constant object.

If later is the case where you are keeping track of total number of Book object constructed so far, then you should have a static data member to keep track of it and you can make getBooksNumber() static as well, and can invoke getBooksNumber() without the object of call.

0

精彩评论

暂无评论...
验证码 换一张
取 消