gpt4 book ai didi

c++ - 如何在 C++ 中使用类修改器将变量加倍

转载 作者:行者123 更新时间:2023-11-30 05:03:57 25 4
gpt4 key购买 nike

这是我的第一篇文章,如果我缺乏礼仪,请见谅。我正在尝试通过引用一个函数来传递一个 Rectangle 对象,然后使用类修改器将尺寸加倍。我没有语法错误,看来我只是错误地调用了 r.setWidth() 和 r.setHeight() 突变器。我认为这会起作用:r.setWidth(w * 2),但它不起作用。任何帮助将非常感激。

#include <iostream>
#include "Rectangle.h"
using namespace std;

Rectangle::Rectangle() { width = 1; height = 1; }
Rectangle::Rectangle(int w, int h) { width = w; height = h; }
Rectangle::~Rectangle() {}
int Rectangle::getWidth() { return width; }
int Rectangle::getHeight() { return height; }
void Rectangle::setWidth(int w) { width = w; }
void Rectangle::setHeight(int h) { height = h; }
int Rectangle::calculateArea() { return width * height; }

// end of Rectangle class implementation

void displayRectangle(Rectangle r);
void doubleAndDisplayRectangle(Rectangle& r);

int main()
{
Rectangle r1, r2;
int w, h; // temp width and height

cout << "Please enter the width and height for the first rectangle: ";
cin >> w >> h;
r1.setWidth(w);
r1.setHeight(h);

cout << "Please enter the width and height for the second rectangle: ";
cin >> w >> h;
r2.setWidth(w);
r2.setHeight(h);

displayRectangle(r1);
displayRectangle(r2);

doubleAndDisplayRectangle(r1);
doubleAndDisplayRectangle(r2);

return 0;
}

void displayRectangle(Rectangle r)
{
int w, h, area;
cout << "Rectangle width = " << r.getWidth() << ", height = " << r.getHeight() << ", and area = " << r.calculateArea() << endl;
}

void doubleAndDisplayRectangle(Rectangle& r)
{
int w, h, area;
cout << "Doubling the rectangle dimensions!" << endl;
/*r.setWidth(w)
r.setHeight(h)*/
cout << "Rectangle width = " << r.getWidth() << ", height = " << r.getHeight() << ", and area = " << r.calculateArea() << endl;
}

如果需要的话,这是我的 h 文件。

#ifndef _RECTANGLE_H
#define _RECTANGLE_H

// declare the Rectangle class
class Rectangle
{
private:
int width = 0, height = 0;
public:
Rectangle();
Rectangle(int w, int h);
~Rectangle();
int getWidth();
int getHeight();
void setWidth(int w);
void setHeight(int h);
int calculateArea();
};

#endif

最佳答案

如果你想将它的当前值加倍,那么你需要使用你的getters 来获取该值,这样你就可以将它加倍。

像这样:

void doubleAndDisplayRectangle(Rectangle& r)
{
cout << "Doubling the rectangle dimensions!" << endl;

int current_width = r.getWidth(); // get current width

r.setWidth(current_width * 2); // set it to double

int current_height = r.getHeight(); // get current height

r.setHeight(current_height * 2); // set it to double

cout << "Rectangle width = " << r.getWidth() << ", height = " << r.getHeight() << ", and area = " << r.calculateArea() << endl;
}

关于c++ - 如何在 C++ 中使用类修改器将变量加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49142895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com