'this' argument has type const but function is not marked const

前端 未结 4 924
灰色年华
灰色年华 2021-02-04 00:44

Okay so I\'m a bit of a noob at C++ and in my second assignment I am required to make classes with public and private arguments etc, etc. Basically the mutator functions won\'t

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 01:18

    If you want to set a value, use the set method. get Methods are only to obtain variables, not to set the inner variables of a class (If they are defined the way you did).

    The correct usage is:

    Customer* CreateCustomer(const string& id, const string& name, const string& address) {
        Customer* temp = new Customer();
    
        temp->set_PhoneNumber( id );
        temp->set_Name( name );
        temp->set_Address( address );
    
        return temp;
    }
    

    Also, you have to alter the interface of your methods:

    class Customer {
    
    private:
        string PhoneNumber_;
        string Name_;
        string Address_;
    
    public:
        string get_PhoneNumber() const {return PhoneNumber_;} // Accessor
        void set_PhoneNumber(const string& x) {PhoneNumber_ = x;} // Mutator
    
        string get_Name() const {return Name_;}
        void set_Name(const string& x) {Name_ = x;}
    
        string get_Address() const {return Address_;}
        void set_Address(const string& x)  {Address_ = x;}
    };
    

    Since you want to set strings and not numbers.

    Using const string& as function arguments is better than string to not copy the string when passing it as an argument. Since it is a const reference, you don't have to fear the function could manipulate the input.

提交回复
热议问题