我有一个包含name和id作为属性的student类。我将它们添加到向量列表中,当迭代列表时,我想为每个对象调用info方法。看看这段代码:
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
class Student{
string _name;
int _id;
public:
Student(string name, int id){
_name = name;
_id = id;
}
void info(){
cout << _name << endl;
cout << _id << endl;
}
friend ostream& operator << (ostream& c,Student &org){
cout << org._name << endl;
cout << org._id << endl;
return c;
}
};
int main(){
vector<Student*> lista;
Student *c1 = new Student("Nihad", 1);
Student *c2 = new Student("Ensar", 2);
Student *c3 = new Student("Amir", 3);
Student *c4 = new Student("Amar", 4);
lista.push_back(c1);
lista.push_back(c2);
lista.push_back(c3);
lista.push_back(c4);
for (vector<Student*>::iterator it = lista.begin(); it != lista.end(); it++){
// calls operator << and prints 4 objects.
cout << **it << endl;
// how do I call info() with it?
*it->info(); // does not work. (exspresion mush have pointer to class type)
}
system("pause");
}
我还定义了运算符&lt;&lt;正如我在代码中评论的那样,它在双重解除引用后工作正常。当我尝试取消引用它以获取指向对象的指针时,我无法通过&#39; - &gt;&#39;来调用info()。这看起来很奇怪。我在这里缺少什么?