在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容
因此可以将虚函数改为纯虚函数。
纯虚函数语法:
virtual 返回值类型 函数名(参数列表)
类中有纯虚函数时,这个类称为抽象类
抽象类特点:
- 无法实例化对象
- 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
#include<iostream>
#include<string>
using namespace std;
class A
{
public:
virtual void f() = 0;//纯虚函数
};
class B :public A
{
public:
virtual void f()//子类必须重写父类中的纯虚函数,否则无法实例化对象
{
cout << "b" << endl;
}
};
void t1()
{
//A a;无法实例化对象
//new a;无法实例化对象
//利用多态技术调用:父类指针或引用指向子类对象
A *a = new B;//new 哪个对象就调用哪个对象的f()函数
a->f();
}
int main()
{
t1();
system("pause");
return 0;
}
实例:
#include<iostream>
#include<string>
using namespace std;
class A
{
public:
virtual void f1() = 0;//纯虚函数
virtual void f2() = 0;//纯虚函数
virtual void f3() = 0;//纯虚函数
void f()
{
f1();
f2();
f3();
}
};
class B :public A
{
public:
virtual void f1()//子类必须重写父类中的纯虚函数,否则无法实例化对象
{
cout << "a" << endl;
}
virtual void f2()//子类必须重写父类中的纯虚函数,否则无法实例化对象
{
cout << "b" << endl;
}
virtual void f3()//子类必须重写父类中的纯虚函数,否则无法实例化对象
{
cout << "c" << endl;
}
};
class C :public A
{
public:
virtual void f1()//子类必须重写父类中的纯虚函数,否则无法实例化对象
{
cout << "d" << endl;
}
virtual void f2()//子类必须重写父类中的纯虚函数,否则无法实例化对象
{
cout << "e" << endl;
}
virtual void f3()//子类必须重写父类中的纯虚函数,否则无法实例化对象
{
cout << "f" << endl;
}
};
void t1(A *a)
{
a->f();
delete a;//防止内存泄漏
}
void t2()
{
t1(new B);
t1(new C);
}
int main()
{
t2();
system("pause");
return 0;
}