- 抽象类可以有构造函数
/**
* @file interesting_facts4.cpp
* @brief 抽象类可以有构造函数
* @author 光城
* @version v1
* @date 2019-07-20
*/
#include<iostream>
using namespace std;
// An abstract class with constructor
class Base
{
protected:
int x;
public:
virtual void fun() = 0;
Base(int i) { x = i; }
};
class Derived: public Base
{
int y;
public:
Derived(int i, int j):Base(i) { y = j; }
void fun() { cout << "x = " << x << ", y = " << y; }
};
int main(void)
{
Derived d(4, 5);
d.fun();
return 0;
}
- 构造函数不能是虚函数,而析构函数可以是虚析构函数
/**
* @file interesting_facts5.cpp
* @brief 构造函数不能是虚函数,而析构函数可以是虚析构函数。
* 例如:当基类指针指向派生类对象并删除对象时,我们可能希望调用适当的析构函数。如果析构函数不是虚拟的,则只能调用基类析构函数。
* @author 光城
* @version v1
* @date 2019-07-20
*/
#include<iostream>
using namespace std;
class Base {
public:
Base() { cout << "Constructor: Base" << endl; }
virtual ~Base() { cout << "Destructor : Base" << endl; }
};
class Derived: public Base {
public:
Derived() { cout << "Constructor: Derived" << endl; }
~Derived() { cout << "Destructor : Derived" << endl; }
};
int main() {
Base *Var = new Derived();
delete Var;
return 0;
}
当基类指针指向派生类对象并删除对象时,我们可能希望调用适当的析构函数。如果析构函数不是虚拟的,则只能调用基类析构函数
4.完整实例¶
- 抽象类由派生类继承实现!
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; } // 实现了fun()函数
};
int main(void)
{
Derived d;
d.fun();
return 0;
}