C++学习日志37------纯虚函数


一、纯虚函数

纯虚函数不可实例化,且其派生类必须实例化。

#include<iostream>
#include"Shape.h"
#include"circle.h"
using std::cout;
using std::endl;

int main()
{
   //Shape s{Color::black,true} 含有纯虚函数,不可以实例化

	Circle c{ 1.2,Color::green,false };
	Shape* p = &c;
	cout << p->getArea() << endl;
	std::cin.get();

}


在这里插入图片描述
结果如上图所示。

二、相关文件

#include "Shape.h"
Shape::Shape(Color color_, bool filled_)
{
	color = color_;
	filled = filled_;
}
Color Shape::getColor() { return color; }
void Shape::setColor(Color color_) { color = color_; }
bool Shape::isFilled() { return filled; }
void Shape::setFilled(bool filled_) { filled = filled_; }

string Shape::toString()
{
	std::array<string, 6> c{ "white"s,"black"s, "red"s, "green"s, "blue"s, "yellow"s, };
	return "Shape :  " + c[static_cast<int>(color)] + "  " + (filled ? "filled"s : "not filled"s);
}
string Shape::colorTostring()
{
	return colorNames[static_cast<int>(color)];
}

string Shape::filledToString()
{
	return (filled ? "filled"s : "not filled"s);
}

#include"circle.h"
Circle::Circle()
{
	radius = 1.0;
}
Circle::Circle(double radius_, Color color_, bool filled_) :Shape{ color_, filled_ }
{
	radius = radius_;
}
 double Circle::getArea() 
{
	return (3.14 * radius * radius);

}
double Circle::getRadius() const
{
	return radius;
}

Circle& Circle::setRadius(double radius)
{
	this->radius = radius;
	return (*this);
}

string Circle::toString()
{
	return ("Circle:radius" + std::to_string(radius) + "," + colorTostring() + " " + filledToString());

}
#pragma once
#include<iostream>
#include<string>
#include<array>
using std::string;
using namespace std::string_literals;
enum class Color
{
	white,black,red,green,blue,yellow,

};

class Shape
{
private:
	Color color{ Color::black };
	bool filled{ false };
	std::array<string, 6>colorNames{ "white"s,"blcak"s, "red"s, "green"s, "blue"s, "yellow"s, };
public:
	Shape() = default;
	Shape(Color color_, bool filled_);

	Color getColor();
	void setColor(Color color_);
	bool isFilled();
	void setFilled(bool filled_);

	string filledToString();
	string colorTostring();
	string toString();

	virtual double getArea() = 0;  //注意:包含纯虚函数,就成为了抽象类.不可以实例化。同时,在其派生类中必须实例化。
};

#pragma once
#include"Shape.h"
class Circle:public Shape
{
private:
	double radius;
public:
	Circle();
	Circle(double radius_, Color color_, bool filled_);
	virtual double getArea() override;
public:
	double getRadius() const;
	Circle& setRadius(double radius);
	string toString();
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@白圭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值