You need to enable JavaScript to run this app. C++如何向结构体内部方法传参,实现基于坐标修改的矩形宽度调整
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.25 07:54:08