【C++grammar】继承与构造test1代码附录
生活随笔
收集整理的這篇文章主要介紹了
【C++grammar】继承与构造test1代码附录
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 1、main.cpp
- 2、circle.cpp
- 3、circle.h
- 4、rectangle.cpp
- 5、rectangle.h
- 6、Shape.h
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);} };總結
以上是生活随笔為你收集整理的【C++grammar】继承与构造test1代码附录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 颐和园入园需要身份证吗
- 下一篇: 推理笔记剧情介绍