崔毅东 C++程序设计入门(上) 第6单元:丹枫虽老犹多态–继承与多态 笔记

本文档是关于C++程序设计的学习笔记,涵盖了构造函数、析构函数、函数重定义、多态与虚函数、访问控制、抽象类与纯虚函数等内容。特别强调了虚函数表在实现运行时多态中的作用,以及纯虚函数在抽象类设计中的意义。
摘要由CSDN通过智能技术生成

在这里插入图片描述在这里插入图片描述在这里插入图片描述
GeometricObject.h

#ifndef GEOMETRICOBJECT_H
#define GEOMETRICOBJECT_H
#include <string>
using namespace std;

class GeometricObject
{
  public:
    GeometricObject();
    GeometricObject(string color, bool filled);
    string getColor();
    void setColor(string color);
    bool isFilled();
    void setFilled(bool filled);
    string toString();

  private:
    string color_;
    bool filled_;
}; // Must place semicolon here

#endif

GeometricObject.cpp

#include "GeometricObject.h"

GeometricObject::GeometricObject()
{
  color_ = "white";
  filled_ = false;
}

GeometricObject::GeometricObject(string color, bool filled)
{
  color_ = color;
  filled_ = filled;
}

string GeometricObject::getColor()
{
  return color_;
}

void GeometricObject::setColor(string color)
{
  color_ = color;
}

bool GeometricObject::isFilled()
{
  return filled_;
}

void GeometricObject::setFilled(bool filled)
{
  filled_ = filled;
}

string GeometricObject::toString()
{
  return "Geometric object | color: " + color_ +
         " | filled: " + ((filled_) ? "true" : "false");
}

DerivedCircle.h

#ifndef DERIVEDCIRCLE_H
#define DERIVEDCIRCLE_H
#include "GeometricObject.h"

class Circle: public GeometricObject
{
public:
  Circle();
  Circle(double);
  Circle(double radius, string color, bool filled);
  double getRadius();
  void setRadius(double);
  double getArea();
  double getPerimeter();
  double getDiameter();

private:
  double radius_;
};  // Must place semicolon here

#endif

DerivedCircle.cpp

#include "DerivedCircle.h"

// Construct a default circle object
Circle::Circle()
{
  radius_ = 1;
}

// Construct a circle object with specified radius
Circle::Circle(double radius)
{
  radius_ = radius;
}

// Return the radius of this circle
double Circle::getRadius()
{
  return radius_;
}

// Set a new radius
void Circle::setRadius(double radius)
{
  radius_ = (radius >= 0) ? radius : 0;
}

// Return the area of this circle
double Circle::getArea()
{
  return radius_ * radius_ * 3.14159;
}

// Return the perimeter of this circle
double Circle::getPerimeter()
{
  return 2 * radius_ * 3.14159;
}

// Return the diameter of this circle
double Circle::getDiameter()
{
  return 2 * radius_;
}

Rectangle.h

#ifndef RECTANGLE_H
#define RECTANGLE_H
#include "GeometricObject.h"

class Rectangle:
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值