为什么在针对类的const成员函数的range-for循环中此const自动变量?

问题描述 投票:1回答:1

我具有以下类声明,并且根据我所了解的与const成员函数有关的知识,const对象不能调用非const成员函数。在range-for循环中,我们使用的是“ const auto animal”,它假定使用的是const对象,因此我认为const对象在调用非const成员函数speak()时应给出编译错误。实际编译,为什么?,也许我对range-for循环的工作原理没有一个清晰的了解...谢谢!

#include <iostream>
#include <string>

class Animal {
protected:
     std::string name_;
     std::string speak_;
public:
    Animal(const std::string &name, const std::string &speak) : name_(name), speak_(speak){}
    const std::string &getName() const  { return name_;}
    std::string speak()  { return speak_;}
};

class Cat : public Animal{
public:
 Cat(const std::string &name) : Animal(name, "meow"){}
};

class Dog : public Animal{
public:
 Dog( const std::string &name) : Animal(name, "woof"){}
};

int main() {
    Cat tom{ "tom" };
    Dog felix{ "felix" };

    Animal *animals[]{ &tom, &felix};
     for (const auto &animal : animals)
         std::cout << animal->getName() << " says " << animal->speak() << '\n';


    return 0;
}
c++ c++11 const auto for-range
1个回答
6
投票

[const auto&在这里成为对Animal*类型的变量的const引用。这意味着您无法更改指针指向的位置,但是指向的值本身仍然是可变的。

替换自动将看起来像:

for (Animal* const& animal : animals)
  // ...

0
投票

输入

for (const auto &animal : animals)

[auto实际上是Animal *

并且大致相当于

for (Animal *animal : animals)

因此该调用没有常量问题。

© www.soinside.com 2019 - 2024. All rights reserved.