首页 > 解决方案 > 如何循环一个类变量数组?

问题描述

仅供参考,我声明了一个类调用 UC,在 UC 内部我声明了一个变量调用course及其数组 [4],这与我现在面临的问题有关。转到我评论为问题的行,我现在只知道该行for(UC &i :: one.course)是错误的,尤其是 UC,这行代码应该做一个 forloopcourse[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、室内设计、大众传播、商业

//这条线不起作用

标签: c++classfor-loopvariables

解决方案


您的问题部分可以如下所示,使用 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 循环中并打印出数组元素。


推荐阅读