您好,欢迎访问代理记账网站
移动应用 微信公众号 联系我们

咨询热线 -

电话 15988168888

联系客服
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

C++(十二)类的继承(重写虚函数)

实现了多边形类,派生了三角形类,实现如下:
头文件:
在这里插入图片描述
源文件
在这里插入图片描述

Polygon.h

#pragma once
#ifndef _Polygon_H_
#define _Polygon_H_
#include <iostream>


class Polygon
{
private:
	float height;
	float width;
	float area;

public:
	Polygon(float h = 0.0, float w = 0.0);
	void Set_Height_Width(float h, float w);
	void Set_Area(float a);
	float GetArea() const;
	float GetHeight() const;
	float GetWidth() const;
	virtual void Print_Polygon_Info() const;
	virtual void Area();
	virtual ~Polygon() {}
};


class Triangle :public Polygon 
{
private:
	std::string name;

public:
	Triangle(float h = 0.0, float w = 0.0, std::string _name = "none");
	Triangle(const Polygon& po, std::string _name = "none");
	virtual void Area();
	virtual void Print_Polygon_Info() const;
};

#endif

Polygon.cpp

#include "Polygon.h"
using namespace std;


Polygon::Polygon(float h, float w) :height(h), width(w) {
	area = 0.0;
}

void Polygon::Set_Height_Width(float h, float w) {
	height = h;
	width = w;
}

float Polygon::GetHeight() const {
	return height;
}

float Polygon::GetWidth() const {
	return width;
}

float Polygon::GetArea() const {
	return area;
}

void Polygon::Set_Area(float a) {
	area = a;
}

void Polygon::Area() {
	area = height * width;
}

void Polygon::Print_Polygon_Info() const {
	cout << "[Polygon_area = height x width] = " << height << " x " << width << " = " << area << endl;
}



Triangle::Triangle(float h, float w, std::string _name) :Polygon(h, w) {
	name = _name;
}

Triangle::Triangle(const Polygon& po, std::string _name) : Polygon(po) {
	name = _name;
}

void Triangle::Area() {
	float area = 0.5 * GetHeight() * GetWidth();
	Set_Area(area);
}


void Triangle::Print_Polygon_Info() const {
	cout << name << " [Tria_area = 0.5 x height x width] = 0.5 x " << GetHeight() << " x " << GetWidth() << " = " << GetArea() << endl;
}

在这里插入图片描述


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进