如何遍历C++类的数组类型成员变量?代码报错求助
解决你的C++范围for循环错误问题
嘿,这个问题很常见,是范围for循环的语法和类型匹配出问题啦!我来给你拆解一下:
错误原因
你写的循环行for(UC &i :: one.course)有两个明显问题:
- 语法错误:范围for循环的分隔符是单冒号
:,不是双冒号::(双冒号是用来访问命名空间或类成员的)。 - 类型不匹配:
one.course是string类型的数组,你却用UC &来定义循环变量,这完全不对应,编译器自然会报错说i未声明(其实本质是语法先错了,导致编译器没法识别变量定义)。
修正方案
把循环行改成下面两种写法都可以:
- 明确指定元素类型:
for(string &i : one.course)
- 用
auto自动推导类型(更简洁推荐):
for(auto &i : one.course)
完整修正后的代码
#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: "; string delim = ""; // 修正后的循环 for(auto &i : one.course){ cout<< delim <<i; delim = ", "; }; 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; };
运行结果
这样修改后,程序就能输出你预期的结果了:
Our College Name: ABC
Our History: 5
Our Founder: Mr.Chong
Our Course: IT, Interior Design, Mass Comm, Business
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

