在c+上打印向量数组+; 我尝试在C++中打印一个向量数组。当我在参数列表中省略“const”和“for each”循环时,程序就会工作。当我插入常量类型限定符时,它会给我一个错误
下面是我的主要函数,该函数调用打印列表:在c+上打印向量数组+; 我尝试在C++中打印一个向量数组。当我在参数列表中省略“const”和“for each”循环时,程序就会工作。当我插入常量类型限定符时,它会给我一个错误,c++,arrays,vector,C++,Arrays,Vector,下面是我的主要函数,该函数调用打印列表: int main() { std::cout << "Hello World\n"; std::vector<Employee> employeeList {}; // Entering employee data buildList(employeeList); //print the list of employees. printList(employeeList);
int main() {
std::cout << "Hello World\n";
std::vector<Employee> employeeList {};
// Entering employee data
buildList(employeeList);
//print the list of employees.
printList(employeeList);
//pause code
int pause;
std::cin >> pause;
return 0;
}
intmain(){
std::cout>暂停;
返回0;
}
以下是打印列表定义:
void printList(std::vector<Employee> &list) {
//use a for each loop to print each employee
int index = 0;
for (auto &element : list) {
std::cout << "\n";
std::cout << "Employee: " <<(index+1)<< std::endl;
element.printEmployee();
index++;
}
}
void打印列表(标准::向量和列表){
//使用for each循环打印每个员工
int指数=0;
用于(自动元素:列表(&E){
std::coutEmployee::printEmployee
的声明不正确。它必须是void Employee::printEmployee()const
,才能在const
上下文中使用
为便于将来参考,您为每个循环调用的称为“基于范围的For循环”或“基于范围的For”。将其称为for each循环可能会与实际算法
std::for each
相混淆,应避免使用。如果添加错误的确切文本,将有助于回答您的问题。如果这是Visual Studio从“输出”选项卡复制文本,而不是从错误列表复制文本,我希望printEmployee()不会声明为void printEmployee()const;
根据显示的代码(这是不够的),我猜错误是ypur编译器告诉您尝试使用Employee::printEmployee()
您忘记将其声明为const
函数。当对象为const
时,您只能访问此对象的const
方法。谢谢。在“void printEmployee()”之后添加“const”使其起作用。