抽象类中:在成员函数内可以调用纯虚函数,在构造函数/析构函数内部不能使用纯虚函数。

如果一个类从抽象类派生而来,它必须实现了基类中的所有纯虚函数,才能成为非抽象类

/**
* @file abstract.cpp
* @brief 抽象类中:在成员函数内可以调用纯虚函数,在构造函数/析构函数内部不能使用纯虚函数
* 如果一个类从抽象类派生而来,它必须实现了基类中的所有纯虚函数,才能成为非抽象类
* @author 光城
* @version v1
* @date 2019-07-20
*/


#include<iostream>
using namespace std;

class A {
public:
virtual void f() = 0; // 纯虚函数
void g(){ this->f(); };
A(){}; //A 的构造函数
};
class B:public A{
public:
void f(){ cout<<"B:f()"<<endl;};
};
int main(){
B b;
b.g();
return 0;
}

3.重要点¶

  • 纯虚函数使一个类变成抽象类
/**
* @file interesting_facts1.cpp
* @brief 纯虚函数使一个类变成抽象类
* @author 光城
* @version v1
* @date 2019-07-20
*/

#include<iostream>
using namespace std;

/**
* @brief 抽象类至少包含一个纯虚函数
*/
class Test
{
int x;
public:
virtual void show() = 0;
int getX() { return x; }
};

int main(void)
{
Test t; //error! 不能创建抽象类的对象
return 0;
}
  • 抽象类类型的指针和引用
/**
* @file interesting_facts2.cpp
* @brief 抽象类类型的指针和引用
* @author 光城
* @version v1
* @date 2019-07-20
*/

#include<iostream>
using namespace std;


/**
* @brief 抽象类至少包含一个纯虚函数
*/
class Base
{
int x;
public:
virtual void show() = 0;
int getX() { return x; }

};
class Derived: public Base
{
public:
void show() { cout << "In Derived \n"; }
Derived(){}
};
int main(void)
{
//Base b; //error! 不能创建抽象类的对象
//Base *b = new Base(); error!
Base *bp = new Derived(); // 抽象类的指针和引用 -> 由抽象类派生出来的类的对象
bp->show();
return 0;
}
  • 如果我们不在派生类中覆盖纯虚函数,那么派生类也会变成抽象类。
/**
* @file interesting_facts3.cpp
* @brief 如果我们不在派生类中覆盖纯虚函数,那么派生类也会变成抽象类。
* @author 光城
* @version v1
* @date 2019-07-20
*/

#include<iostream>
using namespace std;

class Base
{
int x;
public:
virtual void show() = 0;
int getX() { return x; }
};
class Derived: public Base
{
public:
// void show() { }
};
int main(void)
{
Derived d; //error! 派生类没有实现纯虚函数,那么派生类也会变为抽象类,不能创建抽象类的对象
return 0;
}