Operator = Overload with Const Variable in C++

前端 未结 6 1087
刺人心
刺人心 2020-12-31 23:48

I was wondering if you guys could help me.

Here are my .h:

Class Doctor {
   const string name;
   public:
       Doctor();
       Doctor(string nam         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 00:46

    The declaration is Doctor &operator=(const Doctor &other); (i.e., remove the Doctor::)

    from there you'd need to use const_cast<> to remove the const-ness of the member variable to make it work. Note that only heartbreak lies in the path you've chosen.

    I'd recommend removing const from the member declaration and instead making member functions const as necessary to show that they won't affect the object. (For example if you have an accessor member function you could declare that const: string getName() const { return m_name; })

提交回复
热议问题