代码一:
#include "iostream.h"
class Father{
public:
void eat(){
cout<<"父亲喜欢吃米饭"<<endl;
}
void smoking(){
cout<<"喜欢抽烟"<<endl;
}
private:
int weight;
int age;
};
class Son:public Father{
public:
void eat(){
cout<<"儿子喜欢吃粉"<<endl;
}
};
int main(){
Son s;
Son s;
s.eat();
return 0;
}
执行结果:
儿子喜欢吃粉
代码2:
#include "iostream.h"
class Father{
public:
void eat(){
cout<<"父亲喜欢吃米饭"<<endl;
}
void smoking(){
cout<<"喜欢抽烟"<<endl;
}
private:
int weight;
int age;
};
class Son:public Father{
public:
void eat(){
cout<<"儿子喜欢吃粉"<<endl;
}
};
int main(){
Son s;
Father * pf;
pf = &s;
pf->eat();
return 0;
}
执行结果:
父亲喜欢吃饭
输去结果会是下面
父亲爱吃米饭
Press any key to continue
为什么会这样呢!! 把一个子类地址传递给父类指针可以调用成功呢!
1.静态绑定和run-time(运行绑定)。
静态绑定:编译时绑定,通过对象调用
动态绑定:运行时绑定,通过地址实现,根据你给他对象的类型来确认。
下面这段代码调用就是通过下塑造型
int main(){
Son s;
Father f;
Son * pS;
pS = (Son *)&f;
pS->eat();
return 0;
}
虚函数实现动态绑定: