c++ - с++ 如何将变量的值传递给结构内的方法?
问题描述
如何将变量的值传递给结构内的方法?改变矩形宽度的方法。改变宽度需要多少个单位(你需要改变矩形的坐标)。
#include <iostream>
#include <string>
using namespace std;
struct rectl
{
int x1;
int y1;
int x2;
int y2;
int size;
void show()
{
cout << "\n\t"
<< x1<< ","
<< y1;
cout << "\t\t"
<< x2<< ","
<< y1
<< endl;
cout << "\n\n\n";
cout << "\n\t"
<< x1 << ","
<< y2;
cout << "\t\t"
<< x2 << ","
<< y2
<< endl;
}
void resizeWidth(int size)
{
x2 = x2 - size;
}
};
int main()
{
rectl box { 0,10,10,0 };
cout << "How many units to change the width?";
cin >> size >> box.resizeWidth(size); //?????
box.show();
}
解决方案
// u need to declare size first before initialisation from the user.
#include <iostream>
#include <string>
using namespace std;
struct rectl {
int x1;
int y1;
int x2;
int y2;
int size;
void show() {
cout << "\n\t" <<
x1 << "," <<
y1;
cout << "\t\t" <<
x2 << "," <<
y1 <<
endl;
cout << "\n\n\n";
cout << "\n\t" <<
x1 << "," <<
y2;
cout << "\t\t" <<
x2 << "," <<
y2 <<
endl;
}
void resizeWidth
(int size) {
x2 = x2 - size;
}
};
int main() {
rectl box {
0,
10,
10,
0
};
cout << "How many units to change the width?";
int size;
cin >> size;
box.resizeWidth(size); //?????
box.show();
}
推荐阅读
- c++ - 如何让 if() 由 && 而不是 || 分割
- java - spring boot 跟踪更新值
- go - nano 上的 golang 格式搞砸了,而在 vscode 上还可以。nano 格式被推送到 git
- google-maps - 向数据层添加几何图形 - 如何在添加过程中设置特征样式?
- php - 在 localhost laravel 上安装新的 Laravel 源
- sql - ActiveRecord 多对多我应该制作另一个表来保存关系信息吗?
- sql - 在 postgres 中合并查询
- ffmpeg - 高效的命令行来裁剪视频,覆盖另一个裁剪并使用 ffmpeg 缩放结果
- reactjs - 从 fetch 调用变量到 React 渲染函数
- javascript - 如何在表单提交之前立即在无线电输入上设置CustomValidity