标签:style blog http io ar color 使用 sp on
原文地址:理解虚基类、虚函数与纯虚函数的概念
引言
一直以来都没有写过一篇关于概念性的文章,因为我觉得这些概念性的东西书本上都有并且说的也很详细写来也无用,今天突发奇想想写 一写,下面就和大家讨论一下虚基类、虚函数与纯虚函数,一看名字就让人很容易觉得混乱。不过不要紧待看完本文后你就会理解了。
正文
虚基类
在说明其作用前先看一段代码
class A
{
public:
int iValue;
};
class B:public A
{
public:
void bPrintf(){cout<<"This is class B"<<endl;};
};
class C:public A
{
public:
void cPrintf(){cout<<"This is class C"<<endl;};
};
class D:public B,public C
{
public:
void dPrintf(){cout<<"This is class D"<<endl;};
};
void main()
{
D d;
cout<<d.iValue<<endl; //错误,不明确的访问
cout<<d.A::iValue<<endl; //正确
cout<<d.B::iValue<<endl; //正确
cout<<d.C::iValue<<endl; //正确
}
class A
{
public:
int iValue;
};
class B:virtual public A
{
public:
void bPrintf(){cout<<"This is class B"<<endl;};
};
class C:virtual public A
{
public:
void cPrintf(){cout<<"This is class C"<<endl;};
};
class D:public B,public C
{
public:
void dPrintf(){cout<<"This is class D"<<endl;};
};
void main()
{
D d;
cout<<d.iValue<<endl; //正确
}
class A
{
public:
void funPrint(){cout<<"funPrint of class A"<<endl;};
};
class B:public A
{
public:
void funPrint(){cout<<"funPrint of class B"<<endl;};
};
void main()
{
A *p; //定义基类的指针
A a;
B b;
p=&a;
p->funPrint();
p=&b;
p->funPrint();
}
class A
{
public:
virtual void funPrint(){cout<<"funPrint of class A"<<endl;};
};
class B:public A
{
public:
virtual void funPrint(){cout<<"funPrint of class B"<<endl;};
};
void main()
{
A *p; //定义基类的指针
A a;
B b;
p=&a;
p->funPrint();
p=&b;
p->funPrint();
}
class Vehicle
{
public:
virtual void PrintTyre()=0; //纯虚函数是这样定义的
};
class Camion:public Vehicle
{
public:
virtual void PrintTyre(){cout<<"Camion tyre four"<<endl;};
};
class Bike:public Vehicle
{
public:
virtual void PrintTyre(){cout<<"Bike tyre two"<<endl;};
};
void main()
{
Camion c;
Bike b;
b.PrintTyre();
c.PrintTyre();
}
标签:style blog http io ar color 使用 sp on
原文地址:http://www.cnblogs.com/3chimenea/p/4125499.html