Operator = Overload with Const Variable in C++

前端 未结 6 1111
刺人心
刺人心 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:48

    Since your name is const, the only way to "change" it is through the constructor. If you want to use the = operator, you need to "unconst" the string.

    .. if you don't want to "unconst" the string, you could get somewhat equal behaviour by creating a copy-constructor:

    Doctor(const &Doctor d);
    

    .. and implement it:

    Doctor::Doctor(const &Doctor d)
       : name(d.name)
    {
    //Im pretty sure you have access to private attributes here
    // My C+ is a bit rusty :) If not, make a const string getName() method
    }
    

提交回复
热议问题