有一段代码
class Animal{
public:
void Print(){
std::cout<<"this is Animal"<<std::endl;
}
}
void My_Print(const Animal& animal){
animal.Print()
}
这样会报错,因为我们的Animal变量是加了Const标记的,而我们的Print函数是没有加标记的,这说明我们可以通过Print进行修改,而这与Cons标记相违背,所以我们不能在Const类实例中调用非Const方法,这里做以下修改就行:
class Animal{
public:
void Print() const{
std::cout<<"this is Animal"<<std::endl;
}
}
void My_Print(const Animal& animal){
animal.Print()
}