为什么C++类中的set方法无法更新类内成员属性?
问题排查与修复方案
核心问题原因
- 你的
Staff类已经public继承了Person类,但构造函数没有对继承自父类的成员做初始化,你传入的Person实例仅赋值给了Staff类内部额外定义的pIdentifier成员变量,继承自父类的nameOfEmployee、positionOfEmployee还保留默认值no-name、no-position,而你toString方法中直接访问的是继承来的父类成员,自然输出默认值。 - 你在
Staff类中额外定义Person pIdentifier属于冗余设计,继承特性已经让Staff实例自带Person的所有属性,重复存储反而导致数据不一致。 - 额外问题:
toString方法的职责是返回格式化字符串,你在方法内部写了std::cout输出操作,会导致额外的内容提前输出,不符合该方法的设计预期。
修复代码示例
方案1:删除冗余的pIdentifier成员,用父类初始化列表赋值(推荐)
class Staff : public Person { protected: int employeeId; double salary; MechanicalAppliances mechApp; public: Staff() : Person(), employeeId(0), salary(0) {} // 构造函数用初始化列表调用父类Person的拷贝构造,完成父类成员初始化 Staff(Person pId, int eId, double sry, MechanicalAppliances app) : Person(pId), employeeId(eId), salary(sry), mechApp(app) {} Staff(Person pId, int eId, double sry) : Person(pId), employeeId(eId), salary(sry) {} // 其余get/set方法保持不变... std::string toString() { std::string id = std::to_string(employeeId); std::string sal = std::to_string(salary); // 删掉方法内部多余的std::cout操作 std::string msg = "\n----------------------"; msg += "\nEmployee: "; msg += "\nName: " + nameOfEmployee; // 直接访问继承来的父类成员即可 msg += "\nPosition: " + positionOfEmployee; msg += "\nId of Employee: " + id; msg += "\nSalary: " + sal; msg += "\nIn charge of machinery type: " + nameOfMachinery1; return msg; } void print() { std::cout << this->toString(); } }; // main函数不需要改动
方案2:保留pIdentifier成员,修改toString的取值逻辑
如果你一定要保留内部的pIdentifier成员,就修改toString里的取值代码,不要访问继承来的父类成员,改为访问pIdentifier的属性即可:
std::string toString() { std::string id = std::to_string(employeeId); std::string sal = std::to_string(salary); std::string msg = "\n----------------------"; msg += "\nEmployee: "; // 改为从pIdentifier取姓名和职位 msg += "\nName: " + pIdentifier.getNameOfEmployee(); msg += "\nPosition: " + pIdentifier.getPositionOfEmployee(); msg += "\nId of Employee: " + id; msg += "\nSalary: " + sal; msg += "\nIn charge of machinery type: " + nameOfMachinery1; return msg; }
内容的提问来源于stack exchange,提问作者Carlos Alberto Cruz Magaña
相关产品推荐
相关产品推荐

