class Base{
public:
static void statmem() {
std::cout << "in statmem of base\n" << std::endl;
}
};
class Derived final :public Base{
public:
void statmem() const {
std::cout << "in statmem of Derived\n" << std::endl;
}
};
void Derived::f(const Derived& deprived_obj){
Base::statmem();
Derived::statmem();
deprived_obj.statmem();
statmem();
}
今日在使用deprived_obj调用函数时编译没有什么问题,当去掉关键字static以后:
class Base{
public:
void statmem() {
std::cout << "in statmem of base\n" << std::endl;
}
};
class Derived final :public Base{
public:
void statmem() {
std::cout << "in statmem of Derived\n" << std::endl;
}
};
void Derived::f(const Derived& deprived_obj){
Base::statmem();
Derived::statmem();
deprived_obj.statmem();
statmem();
}
编译器报错:
error: passing 'const Derived' as 'this' argument discards qualifiers [-fpermissive]
deprived_obj.statmem();
in call to 'void Derived::statmem()'
百度以后发现,const 的对象调用静态函数没有什么问题,但是调用非const函数就会有问题了。添加了const申明以后,编译通过。
class Base{
public:
void statmem() const{
std::cout << "in statmem of base\n" << std::endl;
}
};
class Derived final :public Base{
public:
void statmem() const {
std::cout << "in statmem of Derived\n" << std::endl;
}
};
void Derived::f(const Derived& deprived_obj){
Base::statmem();
Derived::statmem();
deprived_obj.statmem();
statmem();
}