Skip to content

Instantly share code, notes, and snippets.

@boycgit
Created October 15, 2013 06:34
Show Gist options
  • Save boycgit/6987398 to your computer and use it in GitHub Desktop.
Save boycgit/6987398 to your computer and use it in GitHub Desktop.
子类中调用基类方法(C++)
#include <iostream>
using namespace std;
class Animal
{
public:
void move() const {cout<<"Animal move one step\n";}
void move(int distance) const{
cout<<"Animal move "<<distance;
cout<<" steps."<<endl;
}
protected:
int itsAge;
int itsWeight;
}; /*注意对于类的声明,末尾的分号不要忘记*/
class Dog:public Animal{
public:
void move() const; //覆盖基类的同名函数,
//导致基类的两个重载函数对于基类都不可见了,
//别忘记const,它也是函数特征的一部分
}; /*注意对于类的声明,末尾的分号不要忘记*/
void Dog::move() const{ //不要忘记const关键字
cout<<"In dog ,default move....";
Animal::move(3); //显式调用基类同名函数
}
int main(){
Animal bigAnimal;
Dog fido;
bigAnimal.move(2);
fido.move();
fido.Animal::move(6);
return 0;
}
/**====result========
* Animal move 2 steps.
* In dog ,default move....Animal move 3 steps.
* Animal move 6 steps.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment