关于const迭代器访问的思考

下面这段代码 写出来感觉没什么问题 但无法对函数进行调用

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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值