c++ Access class field from another class syntax -


i have 2 classes

class book { public:      int _pages;     string* _name; }; class shelf { public: int shelfname; int _bookscount; book** _books; }; 

(with more irrelevant function , variables)

and want create function calculate total pages on shelf, new oop tried do:

double shelf:: getavg() {     int sum, i;     (int = 0; < __bookcount-1; i++)// count not considering inedx 0     {         sum += _books[i]._pages;// need fixed<<     } }   

i pretty sure problem last line syntax, can please guide me how correct it? thank in advance

you have multiple errors there.

  • senseless * in _name member
  • typo _bookscount
  • missing return in method getavg
  • missing declaration of method getavg in shelf class
  • and last, major error is, have member book** _books pointer of pointer, access if pointer. should declare _books book* _books.

your code should (can) looks like:

class book {     public:         int _pages;         string _name; };  class shelf { public:     int shelfname;     int _bookscount;     book* _books;      double getavg(); };  double shelf::getavg() {     int sum, i;     (int = 0; < _bookscount; i++)     {         sum += _books[i]._pages;     }      return sum / _bookscount; } 

i hope, helps :)

idea: can use stl container (for example vector) instead of array books in shelf

vector<book> _books; 

because if use * , new (or malloc) initialization, object not allocated on stack, on heap, should delete delete (or free) or cause memory leaks.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -