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
Post a Comment