Created
October 15, 2013 06:34
-
-
Save boycgit/6987398 to your computer and use it in GitHub Desktop.
子类中调用基类方法(C++)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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