[英]C++ How do the class functions store the values of private members and write it into arrays?
I stumbled upon a C++ book in the library and have been following it ever since, trying to do the exercises in that book. 我偶然发现了库中的一本C ++书籍,此后一直在关注它,试图在那本书中进行练习。 The one thing that confused me was the answer to one of the exercises I had gotten wrong.
让我感到困惑的一件事是我弄错了其中一项练习的答案。 I'm a noob and my question is "How do the class functions work in setting values for arrays?".
我是一个菜鸟,我的问题是“类函数如何为数组设置值?”。 If that doesn't make any sense, bear with me.
如果那没有任何意义,请忍受我。 The example I give below is the author's example, not mine.
我在下面给出的示例是作者的示例,而不是我的示例。
#include <iostream>
using namespace std;
class Point {
private: // Data members (private)
int x, y;
public: // Member functions
void set(int new_x, int new_y);
int get_x();
int get_y();
};
int main() {
Point array_of_points[7];
// Prompt user for x, y values of each point.
for(int i = 0; i < 7; ++i) {
int x, y;
cout << "For point #" << i << "..." << endl;
cout << "Enter x coord: ";
cin >> x;
cout << "Enter y coord: ";
cin >> y;
array_of_points[i].set(x, y);
}
// Print out values of each point.
for(int i = 0; i < 7; ++i) {
cout << "Value of array_of_points[" << i << "]";
cout << " is " << array_of_points[i].get_x() << ", ";
cout << array_of_points[i].get_y() << "." << endl;
}
return 0;
}
void Point::set(int new_x, int new_y) {
if (new_x < 0)
new_x *= -1;
if (new_y < 0)
new_y *= -1;
x = new_x;
y = new_y;
}
int Point::get_x() {
return x;
}
int Point::get_y() {
return y;
}
My question is how does the void Point::set function of class Point seem to save the values of the variables x and y in the array. 我的问题是Point类的void Point :: set函数如何将变量x和y的值保存在数组中。 It confuses me because it's like it's storing it but not quite...
它使我感到困惑,因为它就像在存储它,但不完全是...
Note: This is not for an assignment. 注意:这不是用于作业。 Thank you.
谢谢。
Point array_of_points[7];
means that you have created 7 Point
objects in stack area
in memory. 表示您已在内存的
stack area
中创建了7个Point
对象。 Each array element is an object that contains two attributes x
and y
. 每个数组元素都是一个包含两个属性
x
和y
的对象。 Each time you called the method array_of_points[i].set(x, y);
每次您调用方法
array_of_points[i].set(x, y);
means that the i'th
object called set()
method to assign new_x
and new_y
for the object. 表示
i'th
名为set()
方法的对象为该对象分配new_x
和new_y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.