如何更改类中成员函数中的值
How to change a value in a member function within a class?
我正在尝试更改已传递到我的游泳池类的值。我正在尝试将长度、深度和宽度值相乘,以获得我的容量值。但是,当我尝试使用容量成员函数来执行此操作时,它会返回一个垃圾值。我认为我的语法是正确的,所以我是为什么我不确定为什么我会得到垃圾值。下面是我的代码。
这是我的实现文件。
#include <iostream>
#include "SwimmingPoolHeader.h"
using namespace std;
int main()
{
swimmingPool len;
swimmingPool wid;
swimmingPool dep;
swimmingPool cap;
int length;
int width;
int depth;
cout << "Please enter the length of the pool." << endl;
cin >> length;
len.setLength(length);
cout << "Please enter the width of the pool." << endl;
cin >> width;
wid.setWidth(width);
cout << "Please enter the depth of the pool." << endl;
cin >> depth;
dep.setDepth(depth);
cout << "The capacity of the pool is " << cap.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;
};
你知道构造函数是什么吗?为什么不在创建 swimmingPool 对象时添加长度、宽度和深度参数?
swimmingPool(int l = 0, int w = 0, int d = 0) : length(l), width(w), depth(d) {}
然后,您可以像这样创建一个游泳池:
swimmingPool pool(6, 7, 8);
您可能
希望将main()
替换为类似
int main()
{
int length, width, depth;
cout << "Please enter the length of the pool." << endl;
cin >> length;
cout << "Please enter the width of the pool." << endl;
cin >> width;
cout << "Please enter the depth of the pool." << endl;
cin >> depth;
swimmingPool pool;
pool.setLength(length);
pool.setWidth(width);
pool.setDepth(depth);
cout << "The capacity of the pool is " << pool.capacity() << endl;
return 0;
}
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针