首页 > 解决方案 > с++ 如何将变量的值传递给结构内的方法?

问题描述

如何将变量的值传递给结构内的方法?改变矩形宽度的方法。改变宽度需要多少个单位(你需要改变矩形的坐标)。

#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();
}

标签: c++

解决方案


// 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();
}

推荐阅读