虚函数

/*

#include <iostream>

using namespace std;


class A
{
public:
virtual void fun()
{
cout<<"class A.\n";
}
void func1()
{
cout<<"class a.\n";
}
};


class B:public A
{
public:
virtual void fun()
{
cout<<"class B.\n";
}
void func1()
{
cout<<"class b.\n";
}
};


class C:public B
{
public:
virtual void fun()
{
cout<<"calss C.\n";
}
void func1()
{
cout<<"class c.\n";
}
};

//指针和引用一样,必须由小到大,而作用域的使用要由大到小
int main()
{
C c;//对象
c.A::fun();//A

c.B::fun();//B

c.fun();//C


B &rb=c;//引用

rb.fun();//C

rb.B::fun();//B

rb.A::fun();//A


A *pa=&c;//指针
pa->fun();//C
pa->func1();//a


return 0;

}

*/

/*
#include <iostream>
using namespace std;
class A
{
public:
virtual void f1()
{
cout<<"A::f1() called\n";
}
void f2()
{
f1();
}
};


class B:public A
{
public:
void f1()
{
cout<<"B::f1() called\n";
}
void f3()
{
A::f1();
}
};
int main()
{
B b;
b.f2();//B::f1()  

b.f3();//A::f1()
A &ra=b;
ra.f2();//B::f1()
A a=b;
a.f2();//A::f1()
return 0;
}

*/

/*
#include <iostream>
using namespace std;
class Point
{
public:
Point(double i,double j)
{
x=i;
y=j;
}
virtual double Area() const
{
return 0.0;
}
private:
double x,y;
};
class Rectangle:public Point
{
public:
Rectangle(double,double,double,double);
virtual double Area() const
{
return w*h;
}
private:
double w,h;
};
Rectangle::Rectangle(double i,double j,double k,double l):Point(i,j)
{
w=k;
h=l;
}
void func(Point &s)
{
cout<<s.Area()<<endl;
}
int main()
{
Rectangle rec(3.5,15,5.0,19.1);
cout<<rec.Area()<<endl;
func(rec);
return 0;
}
*/

/*
#include <iostream>
using namespace std;
class A
{
public:
virtual void func()
{
cout<<"xxx"<<endl;
}
void fun1()
{
cout<<"bbb"<<endl;
func();
}
};
class B:public A
{
public:
void func()
{
cout<<"vvv"<<endl;
}
void fun1()
{
cout<<"ccc"<<endl;
func();
}
};
int main()
{


A *b=new B;




b->func();
b->fun1();
return 0;
}
*/

/*

#include <iostream>
using namespace std;
class M
{
public:
virtual void f1()
{
cout<<"M::f1() called f2()\n";
f2();
}
virtual void f2()
{
cout<<"M::f2() called f3()\n";
f3();
}
void f3()
{
cout<<"M::f3()\n";
}


};


class N:public M
{
public:
void f2()
{
cout<<"N::f2() called f3()\n";
f3();
}
void f3()
{
cout<<"N::f3() called f4()\n";
f4();
}
void f4()
{
cout<<"N::f4()\n";
}
};


int main()
{
N n;
n.f1();//mf1 nf2 nf3 nf4  
M &rm=n;
rm.f2();//nf2 nf3 nf4 
rm.f3();//mf3  
return 0;
}


*/


基类->派生类1->派生类2.....(虚是对前者的对象,引用,指针而言,前者为虚时就可以屏蔽自己的函数,以达到调用后者函数的目的)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值