【发布时间】:2018-09-25 01:17:33
【问题描述】:
我在图书馆里偶然发现了一本 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 的值保存在数组中。它让我感到困惑,因为它就像是在存储它,但并不完全......
注意:这不是作业。 谢谢。
【问题讨论】: