我在图书馆里偶然发现了一本C ++书,从那时起就一直关注它,试图在那本书中进行练习。让我困惑的一件事就是我遇到错误的一个练习的答案。我是菜鸟,我的问题是“类函数如何为数组设置值?”。如果这没有任何意义,请耐心等待。我在下面给出的例子是作者的例子,而不是我的例子。
#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;
}
我的问题是类Point的void Point :: set函数如何保存数组中变量x和y的值。它让我感到困惑,因为它就像它存储它但不完全......
注意:这不适用于作业。谢谢。