【C++grammar】继承与构造test1代码附录

145 阅读1分钟

目录

1、main.cpp

#include <iostream>
#include <string>
#include "Shape.h"
#include "circle.h"
#include "rectangle.h"

//创建Shape/Circle/Rectangle对象
//用子类对象调用基类函数toString()
using namespace std;
int main() {
    Shape s1{Color::blue,false};
    Circle c1{3.9,Color::green,true};
    Rectangle r1{4.0,1.0,Color::white,true };

    cout << s1.toString() << endl;
    cout << c1.toString() << endl;
    cout << r1.toString() << endl;
    return 0;
}

2、circle.cpp

#include <iostream>
#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;
}

void Circle::setRadius(double radius) {
	this->radius = radius;
}

3、circle.h

#pragma once
#include "Shape.h"
//补全Circle 类,从shape继承
class Circle : public Shape{
	double radius;
public:
	Circle();
	Circle(double radius_, Color color_, bool filled_);
	double getArea();
	double getRadius() const;
	void setRadius(double radius);
};

4、rectangle.cpp

#include "rectangle.h"
Rectangle::Rectangle(double w, double h, Color color_, bool filled_) :width{ w }, height{h}, Shape{ color_,filled_ } {}

double Rectangle::getWidth() const { return width; }
void Rectangle::setWidth(double w) { width = w; }
double Rectangle::getHeight() const { return height; }
void Rectangle::setHeight(double h) { height = h; }

double Rectangle::getArea() const { return width * height; }

5、rectangle.h

#pragma once
#include "Shape.h"
//创建rectangle类,从shape继承
class Rectangle : public Shape {
private:
	double width{1.0};
	double height{1.0};
public:
	Rectangle() = default;
	Rectangle(double w, double h, Color color_, bool filled_);

	//get函数被声明为const类型,表明这个函数本身不去修改类的私有属性
	double getWidth() const;
	void setWidth(double w);
	double getHeight() const;
	void setHeight(double h);

	double getArea() const;
};

6、Shape.h

#pragma once
#include <iostream>
#include <string>
#include <array>
using std::string;
//C++14的字符串字面量
using namespace std::string_literals;
enum class Color {
	white , black , read , green , blue , yellow,
};

class Shape {
private:
	//就地初始化
	Color color{Color::black};
	bool filled{false};
public:
	//无参构造函数,强制由编译器生成
	Shape() = default;
	Shape(Color color_, bool filled_)
	{
		color = color_;
		filled = filled_;
	}
	Color getColor() { return color; }
	void setColor(Color color_) { color = color_; }
	bool isFilled() { return filled; }
	void setFilled(bool filled_) {filled = filled_;}
	string toString() {
		//自动转化为string类型的对象
		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);
	}
};