如何 for 循环类变量数组
How to for loop a array of class variables?
仅供参考,我声明了一个类调用UC,在UC内部我声明了一个变量调用course
,它是一个[4]数组,这与我现在面临的问题有关。转到我评论为问题的行,我现在只知道该行for(UC &i :: one.course)
是错误的,尤其是 UC,这行代码应该执行 forloop 的course[4]
但事实并非如此,它只是显示像i has not been declared
这样的错误。我的预期输出在那里。
#include <iostream>
#include <string>
using namespace std;
class UC{
public:
string name;
int history;
string founder;
string course[4];
};
void print(string, int, string);
int main()
{
UC one;
one.name = "ABC";
one.history = 5;
one.founder = "Mr.Chong";
one.course[0] = "IT";
one.course[1] = "Interior Design";
one.course[2] = "Mass Comm";
one.course[3] = "Business";
print(one.name, one.history, one.founder);
cout<<"Our Course: ";
//problem here//
string delim = "";
for(UC &i :: one.course){
cout<< delim <<i;
delim = ", ";
};
//problem here//
return 0;
}
void print(string r, int x, string y){
cout<<"Our College Name: "<<r<<endl;
cout<<"Our History: "<<x<<endl;
cout<<"Our Founder: "<<y<<endl;
};
我希望输出会像
我们的学院名称:ABC
我们的历史: 5
我们的创始人:庄先生
我们的课程:IT,室内设计,大众通信,商业
//此行不起作用
您的问题部分可以如下所示,使用 for 循环打印出数组:
#include <iostream>
#include <string>
using namespace std;
class UC{
public:
string name;
int history;
string founder;
string course[4];
};
void print(string, int, string);
int main()
{
UC one;
one.name = "ABC";
one.history = 5;
one.founder = "Mr.Chong";
one.course[0] = "IT";
one.course[1] = "Interior Design";
one.course[2] = "Mass Comm";
one.course[3] = "Business";
print(one.name, one.history, one.founder);
cout<<"Our Course: ";
//problem here
int numberofelements = sizeof(one.course)/sizeof(one.course[0]);
for (int i = 0; i < numberofelements; i++){
if(i == numberofelements-1){
cout << one.course[i];
}
else{
cout << one.course[i] << ", ";
}
}
// problem here
return 0;
}
void print(string r, int x, string y){
cout<<"Our College Name: "<<r<<endl;
cout<<"Our History: "<<x<<endl;
cout<<"Our Founder: "<<y<<endl;
};
或者,如果您想要一种更简洁的方法,您可以修改 void print 方法,以采用一个数组参数,该参数被传递到方法主体中的 for 循环中,然后打印出数组元素。
相关文章:
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 类对象数组的问题会导致崩溃
- 将一个类的对象放在另一个类的数组中
- 删除C++中的继承类指针数组
- 需要类 2D 数组 (C++) 的帮助
- 类动态数组错误
- 正确实现类函数数组
- 使用数组类返回数组c++
- C++:声明指向类中数组的指针?
- 动态分配自定义类的数组和重载运算符
- 如何使用 void 函数从类创建数组
- 无法将类对象数组写入/读取到文件
- 如何将数据从文件读取到类的数组中
- 为什么我不能使用已删除或私有析构函数分配类的数组?
- c++ 中的别名变量数组
- 使用类的其他成员变量定义类的成员变量数组
- 如何 for 循环类变量数组
- 如何在继承类中创建父类变量数组作为私有成员
- 如何创建一个类变量数组
- 需要以编程方式初始化类变量数组,我怎么做最好