C++如何向结构体内部方法传参,实现基于坐标修改的矩形宽度调整
核心问题原因
cin仅支持将输入内容读取到变量中,无法直接将输入值作为参数调用结构体方法main函数内未声明存储输入值的局部变量,直接使用的size属于未定义标识符,编译会报错resizeWidth方法的参数名size与结构体成员size重名,存在标识符遮蔽的隐患- 原写法
cin >> size >> box.resizeWidth(size)语法逻辑错误,输入读取和方法调用必须分步执行
修正步骤
- 定义独立局部变量存储用户输入的宽度调整值
- 先通过
cin读取用户输入到该局部变量 - 调用
rectl实例的resizeWidth方法时,将局部变量作为参数传入 - 建议将
resizeWidth的参数名改为更清晰的deltaWidth,避免与结构体成员重名 - 若不需要用结构体存储矩形宽度冗余值,可删除未使用的
size成员
修正后可运行的代码
#include <iostream> using namespace std; struct rectl { int x1; int y1; int x2; int y2; 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 deltaWidth) { x2 = x2 - deltaWidth; } }; int main() { rectl box { 0,10,10,0 }; int inputSize; cout << "How many units to change the width?"; cin >> inputSize; box.resizeWidth(inputSize); box.show(); }
注意:如果需要实现「增加宽度」而非当前的减小宽度逻辑,只需把
resizeWidth里的x2 = x2 - deltaWidth修改为x2 = x2 + deltaWidth即可。
内容的提问来源于stack exchange,提问作者VasoKri
相关产品推荐
相关产品推荐

