我正在尝试创建对象数组并显示它,但是由于某种原因,它给出了错误的输出结果我认为我以错误的方式使用了新运算符,但我不确定出什么问题
#include<bits/stdc++.h>
using namespace std;
class X {
string s;
int b;
public:
void set(string s,int b ) {
this->s = s;
this->b = b;
}
void display() {
cout << this->s << ' ' << this->b << '\n';
}
};
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++) {
int n;
cin >> n;
X* a = new X[n];
for (int j = 0; j < n; j++) {
string s; int b;
cin >> s >> b;
a[i].set(s, b);
}
for (int i = 0; i < n; i++) {
a[i].display();
}
}
}
输入:1个3阿比1omkar 2ritesh 3
输出:礼仪300
#include<bits/stdc++.h>
using namespace std;
class X {
string s;
int b;
public:
void set(string s,int b ) {
this->s = s;
this->b = b;
}
void display() {
cout << this->s << ' ' << this->b << '\n';
}
};
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++) {
int n;
cin >> n;
X *a[n];
for (int j = 0; j < n; j++) {
a[j] = new X;
string s; int b;
cin >> s >> b;
a[j]->set(s, b);
}
for (int i = 0; i < n; i++) {
a[i]->display();
}
}
}
希望这会有所帮助:)
X* a[n];
for(int k = 0 ; i < n ; ++i){
a[k] = new X;
}