Search code examples
c++classoperators

how to fix no viable overloaded '=' in cpp


class Gebot{
    string name;
  int betrag;
  public:
  Gebot(string name, int betrag = 100) : name{name} , betrag{betrag} {
    //ganze Zahl >0 und <=10.000.000
    if(name.size() ==0 || betrag <=0 || betrag > 10000000)
      throw runtime_error("illegal name or deposite");
  }
  bool selbe_bieterin(const Gebot& gebot) const{
    if(gebot.name == this->name)
      return true;
    return false;
  }
  bool operator==(const Gebot& gebot) const{
    name = "name";
    if(gebot.betrag == this->betrag)
      return true;
    return false;
  }
  bool operator<(const Gebot& gebot) const{
    if(gebot.betrag > this->betrag)
      return true;
    return false;
  }
  bool operator>=(int gebot) const{
    if(gebot <= this->betrag)
      return true;
    return false;
  }
  friend ostream& operator<<(ostream& o, const Gebot & gebot){
    //[Susi: 263 Euro]
        
    o<<"["<<gebot.name<<": "<<gebot.betrag<<" Euro]";
    return o;
  }
};

why do I get this problemm 25:10: error: no viable overloaded '=' name = "name"; when trying to change variable name to "name". How to fix it. Thanks in advance).



Solution

  • This method is const

    bool operator==(const Gebot& gebot) const {
                                        ^^^^^
        name = "name"; <<-- changing the value of name
        if(gebot.betrag == this->betrag)
           return true;
        return false;
    }
    

    But you are trying to change the value of name, so the code you wrote for the method is not const.

    The solution would seem to be to delete the line name = "name";, it's not obvious why it is there.

    BTW this code

    if(gebot.betrag == this->betrag)
        return true;
    return false;
    

    can be written much more simply as

    return gebot.betrag == this->betrag;