好的,所以我在C中有点像菜鸟,在我的第二次任务中我需要使用公共和私有参数等进行类等.基本上,mutator函数不起作用,因为显然它们不是const类型的?
这是带有类的头文件:
class Customer { private: string PhoneNumber_; string Name_; string Address_; public: string get_PhoneNumber() const {return PhoneNumber_;} // Accessor const void set_PhoneNumber(unsigned x) {PhoneNumber_ = x;} // Mutator string get_Name() const {return Name_;} const void set_Name(unsigned x) {Name_ = x;} string get_Address() const {return Address_;} const void set_Address(unsigned x) {Address_ = x;} }; // declare the CreateCustomer function prototype with default values Customer* CreateCustomer(const string& id = BLANK,const string& name = BLANK,const string& address = BLANK); Customer* CreateCustomer(const string& id,const string& name,const string& address) { Customer* temp = new Customer(); temp->get_PhoneNumber() = id; // Due to the Accessors and Mutators PhoneNumber,Name and Address are now functions temp->get_Name() = name; temp->get_Address() = address; return temp; }
cout << "\n\nDear "; cout << Charge[0].Holder.set_Name() << " (" << Charge[0].Holder.set_PhoneNumber() << ")"; // DisplayCustomer(customer) ; cout << ",\n" << Charge[0].Holder.set_Address() << "\n\n"
基本上,确切的错误消息是:
Member function ‘set_Name’ not viable: ‘this’ argument has type ‘const
Customer’,but function is not type const
它也发生在set_PhoneNumber和set_Address中.任何帮助将不胜感激!谢谢!
更新:我得到了它的工作.谢谢大家帮助我!
解决方法
如果要设置值,请使用set方法. get方法只是获取变量,而不是设置类的内部变量(如果它们是按照你的方式定义的).
正确的用法是:
Customer* CreateCustomer(const string& id,const string& address) { Customer* temp = new Customer(); temp->set_PhoneNumber( id ); temp->set_Name( name ); temp->set_Address( address ); return temp; }
此外,您必须更改方法的界面:
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;} };
因为你想设置字符串而不是数字.
使用const字符串&因为函数参数优于字符串,所以在将字符串作为参数传递时不复制字符串.由于它是一个const引用,因此您不必担心该函数可能会操纵输入.