【发布时间】:2020-04-15 03:04:39
【问题描述】:
我有以下类声明,根据我所学的有关 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;
}
【问题讨论】:
-
所有的魔法都在
auto之下。如果您尝试在其中打开,您会看到这是对常量指针的引用,而不是对常量指针的引用。这就是为什么你可以调用Animal的非 const 方法
标签: c++ c++11 constants auto for-range