如何 for 循环类变量数组

How to for loop a array of class variables?

本文关键字:类变量 数组 循环类 循环 for 如何      更新时间:2023-10-16

仅供参考,我声明了一个类调用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 循环中,然后打印出数组元素。