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)
在const auto&这里成为常量引用类型的变量Animal*。这意味着您无法更改指针指向的位置,但指向的值本身仍然是可变的。
替换 auto 看起来像:
for (Animal* const& animal : animals)
// ...
Run Code Online (Sandbox Code Playgroud)