【C++】在子类中怎么调用父类的方法

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();
  }
};

猜你喜欢

转载自blog.csdn.net/m0_61629312/article/details/132598007