首页 > 其他 > 详细

cpp面向对象编程

时间:2014-02-23 04:34:49      阅读:385      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣

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

bubuko.com,布布扣

AbstractShape.h

bubuko.com,布布扣
#ifndef ABSTRACTSHAPE_H_
#define ABSTRACTSHAPE_H_
/**
 * 抽象形状类
 */
class AbstractShape
{
private:
    //私有字段
    int edge;

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

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

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

#endif /* ABSTRACTSHAPE_H_ */
bubuko.com,布布扣

AbstractShape.cpp

bubuko.com,布布扣
#include "AbstractShape.h"

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

int AbstractShape::getEdge()
{
    return this->edge;
}
bubuko.com,布布扣

Triangle.h

bubuko.com,布布扣
#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_ */
bubuko.com,布布扣

Triangle.cpp

bubuko.com,布布扣
#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;
}
bubuko.com,布布扣

Rectangle.h

bubuko.com,布布扣
#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_ */
bubuko.com,布布扣

Rectangle.cpp

bubuko.com,布布扣
#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;
}
bubuko.com,布布扣

Main.cpp

bubuko.com,布布扣
#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;
}
bubuko.com,布布扣

编译运行,运行结果:

3
10
4
20

cpp面向对象编程

原文:http://www.cnblogs.com/zfc2201/p/3561069.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!