【问题标题】:C++ How do the class functions store the values of private members and write it into arrays?C++类函数如何存储私有成员的值并将其写入数组?
【发布时间】: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 的值保存在数组中。它让我感到困惑,因为它就像是在存储它,但并不完全......

注意:这不是作业。 谢谢。

【问题讨论】:

    标签: c++ class object


    【解决方案1】:

    Point array_of_points[7]; 表示您在内存中的stack area 中创建了7 个Point 对象。每个数组元素都是一个包含两个属性xy 的对象。每次调用array_of_points[i].set(x, y);方法意味着i'th对象调用set()方法为对象分配new_xnew_y

    【讨论】:

    • 是的,但它如何记住每两个值。从我的想法来看,一旦用户提供输入,x 和 y 就会改变。那么当我把它打印出来时,它不应该能给我所有的价值吗?对不起。你能再解释一下吗?
    • 如果你想知道一个对象是如何存储在内存中的,你可以阅读这里stackoverflow.com/questions/12378271/…
    猜你喜欢
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多