前言
在Java等语言中,都有对接口类的定义,而在C++中,就有抽象类可以代替他的接口类,所以抽象类是不完整的,在面向对象的编程中,他往往是用来做类型隐藏和充当全局变量的角色
定义
- 纯虚函数是一个在基类中说明的虚函数,在基类中没有定义,要求任何派生类都定义自己的版本
- 纯虚函数为各派生类提供一个公共的界面(接口封装和设计,软件模块功能的划分)
形式 virtual 类型 函数名 (参数表)=0;
一个具有纯虚函数的基类称为抽象类
注:
- 抽象类不能建立对象,只能声明抽象类指针
- 抽象类不能作为返回类型
- 抽象类不能作为参数类型
- 可以声明抽象类的引用
下面是案例
class AA
{
public:
virtual void func ()=0; //定义一个虚函数
};
class BB :public AA
{
public:
void func ()
{
cout<<"我最帅"<<endl;
}
};
class CC :public AA //必须要有继承关系
{
public:
void func ()
{
cout<<"你最美"<<endl;
}
};
void func_1 (AA& p) //可以定义抽象类指针
{
p.func(); //多态的实现
}
int main(int argc, char *argv[])
{
BB a; //定义两个子类
CC a1;
func_1(a);
func_1(a1);
return 0;
}
有关多继承的说明
工程上的多继承
- 被实际开发经验抛弃的多继承
- 工程开发中真正意义上的多继承是几乎不被使用的
- 多重继承带来的代码复杂性远多于其带来的便利
- 多重继承对代码维护性上的影响是灾难性的
- 在设计方法上,任何多继承都可以用单继承代替
- 多继承中的二义性和多继承不能解决的问题
多继承的二义性

实际工程经验证明
多重继承接口不会带来二义性和复杂性等问题
多重继承可以通过精心设计用单继承和接口来代替
接口类只是一个功能说明,而不是功能实现。
子类需要根据功能说明定义功能实现。
using namespace std;
class func_1 //接口类的定义
{
public:
virtual int add (int a,int b)=0;
};
class func_2 //接口类的定义
{
public:
virtual int mul (int a,int b)=0;
virtual int div (int a,int b)=0;
virtual int add (int a,int b)=0;//并不会出现二义性
};
class AA
{
public:
virtual int mul (int a,int b)=0;
};
class BB :public AA,public func_1,public func_2 //多继承
{
int a;
int b;
public:
// BB (int a,int b)
virtual int mul (int a,int b)
{
return a-b;
}
virtual int div (int a,int b)
{
return a/b;
}
virtual int add (int a,int b)
{
return a+b;
}
};
class CC :public AA,public func_1,public func_2
{
int a;
int b;
public:
virtual int mul (int a,int b)
{
return 2*(a-b);
}
virtual int div (int a,int b)
{
return 2*(a/b);
}
virtual int add (int a,int b)
{
return 2*(a+b);
}
};
int main(int argc, char *argv[])
{
BB my;
cout<<"a+b="<<my.add(1,2)<<endl;//普通访问
func_1 *my1 =&my;
func_2 *my2 =&my;
cout<<"a+b="<<my1->add(1,2)<<endl;//通过接口访问
cout<<"a-b="<<my2->mul(1,2)<<endl;
CC ni;
func_1 *ni1 =∋ //指向不同的对象
cout<<"~a+b="<<ni1->add(1,2)<<endl;//通过接口访问
return 0;
}
1602





