cpp面向对象编程

如下图,先建好文件, 这里用的是Visual studio 2010

当然也可以用eclipse for cpp,如下图:

AbstractShape.h

#ifndef ABSTRACTSHAPE_H_
#define ABSTRACTSHAPE_H_
/**
 * 抽象形状类
 */
class AbstractShape
{
private:
    //私有字段
    int edge;

public:
    //构造函数
    AbstractShape(int edge);

    //实例方法,子类继承后可以重用
    int getEdge();

    //纯虚函数,父类没有实现,调用时只会调用子类的实现
    virtual int calcArea()=0;
};

#endif /* ABSTRACTSHAPE_H_ */

AbstractShape.cpp

#include "AbstractShape.h"

AbstractShape::AbstractShape(int edge)
{
    this->edge = edge;
}

int AbstractShape::getEdge()
{
    return this->edge;
}

Triangle.h

#include "AbstractShape.h"
#ifndef TRIANGLE_H_
#define TRIANGLE_H_

/**
 * 三角形类,继承自抽象形状类
 */
class Triangle: public AbstractShape
{
private:
    //私有字段
    int bottom;
    int height;

public:
    //构造函数
    Triangle(int bottom, int height);

    //重写父类同名方法,用于实现多态性
    int calcArea();
};

#endif /* TRIANGLE_H_ */

Triangle.cpp

#include "AbstractShape.h"
#include "Triangle.h"

Triangle::Triangle(int bottom, int height) :
    AbstractShape(3)
{
    this->bottom = bottom;
    this->height = height;
}

int Triangle::calcArea()
{
    return this->bottom * this->height / 2;
}

Rectangle.h

#include "AbstractShape.h"
#ifndef RECTANGLE_H_
#define RECTANGLE_H_

/**
 * 矩形类,继承自形状类
 */
class Rectangle: public AbstractShape
{
private:
    //私有字段
    int bottom;
    int height;

public:
    //构造函数
    Rectangle(int bottom, int height);

    //重写父类同名方法,用于实现多态性
    int calcArea();
};

#endif /* RECTANGLE_H_ */

Rectangle.cpp

#include "AbstractShape.h"
#include "Rectangle.h"

Rectangle::Rectangle(int bottom, int height) :
    AbstractShape(4)
{
    this->bottom = bottom;
    this->height = height;
}

int Rectangle::calcArea()
{
    return this->bottom * this->height;
}

Main.cpp

#include "AbstractShape.h"
#include "Triangle.h"
#include "Rectangle.h"
#include <iostream>
using namespace std;

int main()
{
    Triangle triangle = Triangle(4, 5);
    cout << triangle.getEdge() << endl;
    cout << triangle.calcArea() << endl;

    Rectangle rectangle = Rectangle(4, 5);
    cout << rectangle.getEdge() << endl;
    cout << rectangle.calcArea() << endl;

    return 0;
}

编译运行,运行结果:

3
10
4
20
原文地址:https://www.cnblogs.com/zfc2201/p/3561069.html