下面这段代码 写出来感觉没什么问题 但无法对函数进行调用
class player {
public:
player(string name, int age, int high) {
this->name = name;
}
string name;
void printff()
{
cout << "姓名:" << this->name;
}
};
void print(const list<player>& L) {
for (list<player>::const_iterator it = L.begin(); it != L.end(); it++) {
it->printff();
}
}
三种解决方法
1.解引用迭代器获得对象引用 在调用
2.去掉const
3.在成员函数后面加const
这里迭代器可以看作指针,加const后就是常量指针,常量指针(const 指针)只能调用常量成员函数。当你有一个指向常量对象的指针时,即使你的函数不对值进行修改,为了保证对象的状态不被修改,只能通过该指针调用常量成员函数。
三种解决方法代码(水)
- 1
void print(const list<player>& L) {
for (list<player>::const_iterator it = L.begin(); it != L.end(); it++) {
const player& p = *it; // 解引用迭代器获取对象引用
p.printff(); // 调用对象的成员函数
}
}
- 2
void print(list<player>& L) {
for (list<player>::iterator it = L.begin(); it != L.end(); it++) {
it->printff();
}
}
- 3
class player {
public:
player(string name, int age, int high) {
this->name = name;
}
string name;
void printff() const
{
cout << "姓名:" << this->name;
}
};
void print(const list<player>& L) {
for (list<player>::const_iterator it = L.begin(); it != L.end(); it++) {
it->printff();
}
}