如何在类成员函数中修改值?swimmingPool类容积计算返回垃圾值求助
问题:swimmingPool类计算容积返回垃圾值的原因及修复方案
嘿,我一眼就看出问题所在啦——你错误地创建了四个完全独立的swimmingPool对象:len、wid、dep、cap。每个对象都有自己私有的length、width、depth成员变量,它们之间完全不共享数据。
你给len设置了长度,给wid设置了宽度,给dep设置了深度,但cap对象的这三个变量从来没被赋值过,它们的初始值是内存里的随机垃圾数据,所以调用cap.capacity()时,自然会返回毫无意义的垃圾值。
修复后的代码
只需要创建一个swimmingPool对象,然后给它的三个属性分别赋值,再调用它的容积计算方法就可以了:
修改后的实现文件
#include <iostream> #include "SwimmingPoolHeader.h" using namespace std; int main() { swimmingPool pool; // 只创建一个泳池对象 int length; int width; int depth; cout << "Please enter the length of the pool." << endl; cin >> length; pool.setLength(length); cout << "Please enter the width of the pool." << endl; cin >> width; pool.setWidth(width); cout << "Please enter the depth of the pool." << endl; cin >> depth; pool.setDepth(depth); cout << "The capacity of the pool is " << pool.capacity() << endl; system("pause"); return 0; }
头文件(无需修改)
class swimmingPool { public: void setLength(int l) { length = l; } int getLength() { return length; } void setWidth(int w) { width = w; } int getWidth() { return width; } void setDepth(int d) { depth = d; } int getDepth() { return depth; } int capacity() { return length * depth * width; } private: int length; int width; int depth; };
额外优化建议
为了避免类似的未初始化问题,你可以给类添加构造函数,在创建对象时就初始化成员变量:
// 头文件中添加构造函数 class swimmingPool { public: // 默认构造函数,初始化成员为0 swimmingPool() : length(0), width(0), depth(0) {} // 带参数的构造函数,直接初始化泳池尺寸 swimmingPool(int l, int w, int d) : length(l), width(w), depth(d) {} // 原有的set/get方法和capacity方法... };
这样即使忘记调用set方法,成员变量也会有默认的0值,不会返回垃圾数据。
内容的提问来源于stack exchange,提问作者Wyatt Bush
相关产品推荐
相关产品推荐

