为什么这个 const auto 变量在 range-for 循环中为类的 const 成员函数编译?

lea*_*ude 1 c++ constants auto c++11 for-range

我有以下类声明,根据我所了解的与 const 成员函数相关的知识,const 对象不能调用非常量成员函数。在 range-for 循环中,我们使用了“const auto animal”,它假设使用的是 const 对象,所以我认为在调用非常量成员函数 speak() 时,const 对象应该会给出编译错误,但它实际上编译,为什么?,也许我对 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;
}
Run Code Online (Sandbox Code Playgroud)

N. *_*ead 6

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

替换 auto 看起来像:

for (Animal* const& animal : animals)
  // ...
Run Code Online (Sandbox Code Playgroud)

  • 您要循环的整体类型是“Animal*”。然后,“auto”变成“Animal*”,我们向其添加一个常量引用。一种思考方法是将“Animal*”替换为“using Animal_ptr = Animal*”;然后,`const auto&amp;` 变成 `const Animal_ptr&amp;`:也就是说,指针是 const,而不是内部发生的任何内容。 (2认同)