Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis0
Constructor
Hi. How to complete the declaration of these following class, such that the class can keep track of how many objects have been instantiated since the beginning of a program that uses it? : //answers on the wide blank spaces class Book { public: const char * getTitle() const { return m_title; } void setTitle(const char * t) { strcpy(m_title, t) } private: char m_title[256]; };
2 Respostas
+ 1
Use a static member that is to be incremented by one every time when the constructor is called. That is local to a class instead of a single instance, and will be updated whenever a new object calls the Constructor.
Eg :
class Book
{
static int book_ct;
char m_title[256];
public :
Book() { book_ct++; }
// More code...
};
int Book::book_ct=0;
To check its value after some operation, you will have to use a static member, like :
static void print_count()
{ cout<<book_ct<<" Books Exist\n"; }
And then you call it in main like this :
int main()
{
Book books[5];
Book::print_count();
// More code follows...
}
0
thank you