纯虚函数只能在派生类中实现,虚函数可以在基类中实现。
用父类的指针在运行时刻来调用子类。父类指针通过虚函数来决定运行时刻到
底是谁而指向谁的函数。
有纯虚函数的类是抽象类,不能生成对象,只能派生。他派生的类的纯虚函数
没有被改写,那么,它的派生类还是个抽象类。定义纯虚函数就是为了让基类
不可实例化。
[flydream@flydream C++]$ cat PureVirtual.cpp
#include <iostream>
using namespace std;
class Base
{
public:
virtual int add(int a, int b) = 0;
virtual int sub(int a, int b) = 0;
};
class Derived : public Base
{
public:
int add(int a, int b)
{
return (a + b);
}
//int sub(int a, int b)
//{
// return (a - b);
//}
};
class Next : public Derived
{
public:
int sub(int a, int b)
{
return (a - b);
}
};
int main(int argc, char *argv[])
{
Derived a;
Next n;
return 0;
}
[flydream@flydream C++]$ g++ -g -Wall PureVirtual.cpp
PureVirtual.cpp: In function ‘int main(int, char**)’:
PureVirtual.cpp:34:10: error: cannot declare variable ‘a’ to be of abstract type ‘Derived’
PureVirtual.cpp:10:7: note: because the following virtual functions are pure within ‘Derived’:
PureVirtual.cpp:8:15: note: virtual int Base::sub(int, int)
[flydream@flydream C++]$
用父类的指针在运行时刻来调用子类。父类指针通过虚函数来决定运行时刻到
底是谁而指向谁的函数。
有纯虚函数的类是抽象类,不能生成对象,只能派生。他派生的类的纯虚函数
没有被改写,那么,它的派生类还是个抽象类。定义纯虚函数就是为了让基类
不可实例化。
[flydream@flydream C++]$ cat PureVirtual.cpp
#include <iostream>
using namespace std;
class Base
{
public:
virtual int add(int a, int b) = 0;
virtual int sub(int a, int b) = 0;
};
class Derived : public Base
{
public:
int add(int a, int b)
{
return (a + b);
}
//int sub(int a, int b)
//{
// return (a - b);
//}
};
class Next : public Derived
{
public:
int sub(int a, int b)
{
return (a - b);
}
};
int main(int argc, char *argv[])
{
Derived a;
Next n;
return 0;
}
[flydream@flydream C++]$ g++ -g -Wall PureVirtual.cpp
PureVirtual.cpp: In function ‘int main(int, char**)’:
PureVirtual.cpp:34:10: error: cannot declare variable ‘a’ to be of abstract type ‘Derived’
PureVirtual.cpp:10:7: note: because the following virtual functions are pure within ‘Derived’:
PureVirtual.cpp:8:15: note: virtual int Base::sub(int, int)
[flydream@flydream C++]$