抽象类与纯虚函数
在这个类当中,我们定义了一个普通的虚函数,并且也定义了一个纯虚函数。
纯虚函数:从上面的定义可以看到,纯虚函数就是没有函数体,同时在定义的时候,其函数名后面要加上“= 0”。
1.在类成员方法的声明(不是定义)语句前面加个单词:virtual,她就会摇身一变成为虚函数。
2.虚函数的声明语句末尾中加个 =0 ,她就会摇身一变成为纯虚函数。
3.子类可以重新定义基类的虚函数,我们把这个行为称之为复写(override)。
附上一个c++期末考试的题目,抽象类得记住!
请编写一个抽象类Shape,在此基础上派生出类Rectangle和Circle,
二者都有计算对象面积的函数getArea()、计算对象周长的函数getPerim()
#include
using namespace std;
class Shape{
public:
Shape(){}
~Shape(){}
public:
virtual double getArea() const = 0;
virtual double getPerim() const = 0;
private:
};
class Rectangle : public Shape{
public:
Rectangle(double _length, double _width) : length(_length), width(_width){}
~Rectangle(){}
public:
double getArea() const {return length * width;}
double getPerim() const {return 2 * (length + width);}
private:
double length;
double width;
};
class Circle : public Shape{
public:
Circle(double _radius) : radius(_radius){}
~Circle(){}
public:
double getArea() const {return radius * radius * M_PI;}
double getPerim() const {return 2 * M_PI * radius;}
private:
double radius;
};
int main() {
Rectangle * rec = new Rectangle(2, 3);
Circle * cir = new Circle(3);
cout getArea() << endl;
cout getPerim() << endl;
cout getArea() << endl;
cout getPerim() << endl;
}string
string newname(char[], pos) 切割0-pos的字符并存入newname
string newname(char[], pos, pos+length) 切割从下标为pos开始的length个长度的字符存入newname
#include using namespace std; char ID[10]; cin >> ID; string year(ID, 4); string department(ID, 4, 2); string c(ID, 6, 2); cout << "year:" << year << endl << "department:" << department << endl << "class:" << c << endl;

京公网安备 11010502036488号