【发布时间】:2018-06-29 16:18:07
【问题描述】:
我正在尝试像往常一样使用 for 循环打印指针数组的值,并且我设法打印了存储在一个对象中的值,但无法打印存储在另一个对象中的值。我的类在 Predmet.h 中定义:
#include <iostream>
#include <string>
using namespace std;
class Predmet
{
public:
int numberOfItems;
string name;
Predmet();
~Predmet();
};
和 Plaza.h:
class Plaza
{
public:
int length;
double x;
double y;
Plaza();
~Plaza();
};
我的 main.cpp 看起来像这样:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include "Plaza.h"
#include "Predmet.h"
using namespace std;
int main() {
int n, m;
int *numberOfBeaches;
Plaza *obj1;
Predmet *obj2;
cout << "Enter number of beaches (N): ";
cin >> n;
obj1 = new Plaza[n];
for (int i = 0; i < n; i++) {
cout << "Enter length and coordinates for " << i + 1 << ". beach: " << endl;
cin >> obj1[i].length;
cin >> obj1[i].x >> obj1[i].y;
}
cout << endl;
cout << "Enter number of items (M): ";
cin >> m;
obj2 = new Predmet[m];
numberOfBeaches = new int[n];
for (int i = 0; i < m; i++) {
cout << "Enter ordinal number of beach for " << i + 1 << ". item: ";
cin >> numberOfBeaches[i];
cout << "Enter how much of item you have and name of the item: ";
cin >> obj2[i].numberOfItems >> obj2[i].name;
}
int *p;
for (int i = 0; i < n; i++) {
p = find(numberOfBeaches, numberOfBeaches + n, i + 1);
if (*p == i + 1) {
for (int j = 0; j < m; j++) {
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].length << " - predmeti: " << obj2[j].numberOfItems << " " << obj2[j].name << endl;
}
}
else {
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].length << " - predmeti: " << endl;
}
}
delete[] obj1;
delete[] obj2;
delete[] numberOfBeaches;
system("pause");
return 0;
}
在我为 obj2[i].kolicina 和 obj2[i].opis 添加打印之前,一切都正常工作,我得到奇怪的打印结果,并抛出了这个异常,如下所示:
我做错了什么?提前致谢。 编辑:
根据 cmets 的建议,我设法修复了代码(上面的更新版本)以正确方式打印它,只有当我有 M > 1(例如 M = 2)我得到重复打印的行?我该如何解决?
【问题讨论】:
-
您正在访问
brojPlaze最多 m,是 n -
M 可以 > N,但不是必须的。在我的测试用例中,N = 2 和 M = 1。
-
那么轮到
obj2最多访问n...你为什么不使用vectors,顺便说一句? -
您能否将您的程序尽可能多地翻译成英文,或者至少添加一个简短的解释来说明它应该做什么?
-
这是大学作业,有人告诉我不要在这个例子中使用向量。我将代码更新为英文,检查一下,当你翻译成英文时,Plaza = Beach 类和 Predmet = Item 类。 X 和 Y 是每个海滩的坐标。