C++带有指针的函数调用问题

本文探讨了C++中关于指针调用函数的问题,特别是涉及多态性的情况。当Fish子类对象通过Animal父类指针调用breathe方法时,由于没有使用virtual关键字,实际调用了Animal的breathe方法。通过添加virtual,可以实现多态性,使得在运行时根据对象的实际类型调用相应的方法,即动态绑定。
摘要由CSDN通过智能技术生成
#include<iostream.h>
class Animal{
public:
	Animal(int height,int weight){
		//cout<<"animal construct"<<endl;
	}
	~Animal(){
		//cout<<"animal disconstruct"<<endl;
	}
	void eat(){
		cout<<"animal eat"<<endl;
	}
	void sleep(){
		cout<<"animal sleep"<<endl;
	}
	void breathe(){
		cout<<"animal breath"<<endl;
	}
};
class Fish: public Animal{
public:
	Fish():Animal(400,300),a(1){  //子类中向父类带参数的构造函数传递参数的一种方式
//		cout<<"fish construct"<<endl;
	}
	~Fish(){
//		cout<<"fish disconstruct"<<endl;
	}
	void breathe()
	{
		//Animal::breathe(); // : 冒号是作用域标识符,主要用于表示是属于哪一个类的.
		cout<<"fish bubble"<<endl;
	}
	
private:
	const int a;  //常量是必须要进行初始化的
};
void fn(Animal *pAn){
	pAn->breathe();
}
void main(){
	Fish fs;
	//fs.breathe();
	Animal *pAn;
	pAn = &fs;
	fn(pAn);
}

程序运行结果如下:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值