您正在遍历“MyClass”的向量,这可能是用户定义的类型。因此,您必须告诉编译器,您对“MyClass”类的哪些数据感兴趣。下面是示例代码 - 仅用于理解目的
// Temp_Practice.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<memory>
#include<ostream>
#include <vector>>
using namespace std;
// This example is just for understanding/Demo purpose.
// it will not run on any compiler
class MyClass {
public:
std::string _name;
std::string _address;
int _age;
// Constructor
public:
MyClass() {}
MyClass(std::string name, std::string address, int age) :_name(name), _address(address), _age(age) {}
//Destructor
//..
// other stuff
friend ostream& operator << (ostream& os, std::string _input);
};
ostream& operator << (ostream& os, std::string _input)
{
os << _input.c_str();
return os;
}
int main()
{
std::vector<MyClass> vecMyClass;
MyClass temp("AA", "BB", 1);
vecMyClass.push_back(temp);
MyClass temp1("CC", "DD", 2);
vecMyClass.push_back(temp1);
MyClass temp2("EE", "FF", 3);
vecMyClass.push_back(temp2);
MyClass temp3("GG", "HH", 4);
vecMyClass.push_back(temp3);
MyClass temp4("II", "JJ", 5);
vecMyClass.push_back(temp4);
MyClass temp5("KK", "LL", 6);
vecMyClass.push_back(temp5);
std::vector<MyClass>::iterator itr;
for ( itr = vecMyClass.begin(); itr != vecMyClass.end(); ++itr)
{
// Compiler throws error; it does not know what programer wants to print. So its
// programer responsiblity to let compiler know what to be printed
//std::cout << itr << std::endl; // Error!!!!
// Correct Code
std::cout << itr->_name << itr->_address << itr->_age << std::endl;
}
return 0;
}