我有以下类声明,并且根据我所学的与const成员函数有关的知识,const对象不能调用非const成员函数。在range-for循环中,我们使用的是“常量自动动物”,它大概使用了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;
}

最佳答案

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

更换汽车看起来像:

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

07-28 02:02
查看更多