Error Writing a Copy constructor in C++ -


i trying write copy constructor class these 2 error messages, cannot decipher. can please tell me doing incorrect?

class critter     {      public:         critter(){}         explicit critter(int hungerlevelparam):hungerlevel(hungerlevelparam){}         int gethungerlevel(){return hungerlevel;}          // copy constructors         explicit critter(const critter& rhs);         const critter& operator=(const critter& rhs);      private:         int hungerlevel;     };  critter::critter(const critter& rhs)     {     *this = rhs;     }  const critter& critter::operator=(const critter& rhs)     {     if(this != &rhs)         {         this->hungerlevel = rhs.gethungerlevel(); // error: object has type qualifier not compatible member function         }     return *this;     }  int _tmain(int argc, _tchar* argv[])     {     critter acritter2(10);     critter acritter3 = acritter2; // error : no suitable copy constructor     critter acritter4(acritter3);     return 0;     } 

you need int gethungerlevel() const {return hungerlevel;}

otherwise, aren't allowed call gethungerlevel() using reference-to-const rhs.

also, can't copy-initialization explicit copy constructor, direct initialization: critter acritter3(acritter2);

probably want make copy ctor non-explicit rather change definition of acritter3, call.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -