gpt4 book ai didi

C++ 类函数如何存储私有(private)成员的值并将其写入数组?

转载 作者:行者123 更新时间:2023-11-28 04:32:30 24 4
gpt4 key购买 nike

我在图书馆偶然发现了一本 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 的值保存在数组中。这让我感到困惑,因为它就像是在存储它,但又不完全......

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

最佳答案

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

illustration

关于C++ 类函数如何存储私有(private)成员的值并将其写入数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52489298/

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