gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:11:09 24 4
gpt4 key购买 nike

我有以下类声明,并且根据我所学的与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)
// ...

关于c++ - 为什么在针对类的const成员函数的range-for循环编译中使用此const自动变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com