gpt4 book ai didi

c++ - 整数未被复制到对象中的数组

转载 作者:行者123 更新时间:2023-11-28 04:10:36 25 4
gpt4 key购买 nike

我有两个类,类 point 包含一个 int x 和 y 值,类 rectangle 包含其他值并且是类 point 的友元。我正在尝试接收所有变量的用户输入,然后将数据传输到类矩形内的数组中。

x 和 y 值未正确传输到矩形类中的点变量成员。

我是类的新手,我知道这与我如何访问点类中的变量有关。

  //class declarations in header file

class point {
int x, y;

public:
point();
void setX(point p1, int y);
void setY(point p1, int y);
const int getX(point p);
const int getY(point p);

};
class rectangle{
int width = 0, length = 0;
point tlCorner;
int corners[8]{0};

public:
const int getWidth(rectangle rec);
const int getLength(rectangle rec);
void setWidth(rectangle rec,int w);
void setLength(rectangle rec,int l);
void userIn(rectangle &rec);
void printCoords(rectangle rec);
rectangle setCorners(rectangle &rec);
friend class point;
};


//mutator functions for point class
void point ::setX(point p1, int x){
x = x;
}
void point ::setY(point p1, int y){
y = y;
}



//user input function that takes in inputs and sets inputs into rectangle
object
void rectangle::userIn(rectangle &rec){
int x, y, width, length;
cout <<"Enter X coordinate" << endl;
cin >> x;
rec.Corner.setX(rec.Corner, x);
cout <<"Enter Y coordinate" << endl;
cin >> y;
rec.Corner.setY(rec.Corner, y);
cout << "Enter length" << endl;
cin >> width;
rec.setLength(rec, length);
cout << "Enter width" << endl;
cin >> width;
rec.setWidth(rec, width);


}

我当前的输出是:

Enter rectangle 1 values
Enter X coordinate
2
Enter Y coordinate
4
Enter length
2
Enter width
3
Rectangle 1 coordinates
Top left corner: (0,0)
Bottom left corner: (0,-3)
Bottom right corner: (0,-1)
Top right corner: (0,0)

最佳答案

void point::setY(point p1, int y){
y = y;
}

应该是

void point::setY(point p1, int y){
this->y = y;
}

y成员或y参数应重命名。

p1是没用的,可以去掉。

很简单:

void point::setY(int y){
this->y = y;
}

用法类似于:

point p;

p.setY(42);

关于c++ - 整数未被复制到对象中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57898495/

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