虚函数

#include <iostream>
#include <cstdio>

using namespace std;


void t1(){
	class A{
	public	:
		void f1(){
			cout<<"A--f1\n";
		}
		
		void f1(int a){
			cout<<"A--f1--int\n";
		} 
		void f2(){
			cout<<"A--f2\n";
		}
	};
	
	class B:public A{
	public	:
		void f1(){
			cout<<"B--f1\n"; 
		}
		
		
		/*使用类名访问基类成员函数 
			在成员函数被复写的情况下,基类本来可以继承的其他同名重载函数都会被屏蔽
			而不会继承 
		*/
		void showA(){
			A::f1();
		} 
	};
	
	A a;
	B b;
	a.f1();		
//	b.f1(2);	//报错 
	b.showA(); 
	//通过派生类访问基类成员函数,必须是public 继承 
	b.A::f1();
	b.A::f2();
} 


void t2(){
	class A{
	public:
		void show(){
			cout<<"A\n";
		}
	};
	
	
	class B : public A{
	public :
	void show(){
			cout<<"B\n"; 
		}	
	};
	
	
	A* p = new B();		//只能调用A的成员函数 
	p->show();
	cout<<sizeof(A)<<endl;
} 


void t3(){
	class A{
	public:
		virtual void show(){
			cout<<"A\n";
		}
	};
	
	
	class B : public A{
	public :
	void show(){
			cout<<"B\n"; 
		}	
	};
	
	
	A* p = new B();		//只能调用A的成员函数 
	p->show();
	cout<<sizeof(A)<<endl;
} 
int main(int argc, char *argv[])
{	t2();
	t3();
	return 0;
}

 

转载于:https://my.oschina.net/ahaoboy/blog/880345

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值