2023年8月31日,周四上午
目录
在C++中,子类可以以以下几种方式调用父类的方法:
使用父类作用域运算符::
这种方法既可以在子类没有重写父类方法时使用,
也可以在子类重写了父类方法时使用。
子类没有重写父类方法时
class Parent {
public:
void func() {
// ...
}
};
class Child: public Parent {
public:
void callParentFunc() {
Parent::func();
}
};
子类重写了父类方法时
class Parent {
public:
void func() {
std::cout<<"调用父类的方法"<<std::endl;
}
};
class Child: public Parent {
public:
void func() {
Parent::func();
}
};
使用this指针调用
这种方法只能在子类没有重写父类方法时使用。
子类没有重写父类方法时
class Parent {
public:
void func() {
// ...
}
};
class Child: public Parent {
public:
void callParentFunc() {
this->func();
}
};