实验4

实验任务1

源代码:

GradeCalc.hpp:

#pragma once

#include <vector>
#include <array>
#include <string>

class GradeCalc {
public:
    GradeCalc(const std::string &cname);      
    void input(int n);
    void output() const;
    void sort(bool ascending = false);
    int min() const;
    int max() const;
    double average() const;
    void info();

private:
    void compute();

private:
    std::string course_name;
    std::vector<int> grades;
    std::array<int, 5> counts;
    std::array<double, 5> rates;
    bool is_dirty;
};

GradeCalc.cpp:

#include <algorithm>
#include <array>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

#include "GradeCalc.hpp"

GradeCalc::GradeCalc(const std::string &cname):course_name{cname},is_dirty{true} {
    counts.fill(0);
    rates.fill(0);   
}

void GradeCalc::input(int n) {
    if(n < 0) {
        std::cerr << "无效输入! 人数不能为负数\n";
        std::exit(1);
    }

    grades.reserve(n);

    int grade;

    for(int i = 0; i < n;) {
        std::cin >> grade;

        if(grade < 0 || grade > 100) {
            std::cerr << "无效输入! 分数须在[0,100]\n";
            continue;
        }
        
        grades.push_back(grade);
        ++i;
    }

    is_dirty = true;
}

void GradeCalc::output() const {
    for(auto grade: grades)
        std::cout << grade << ' ';
    std::cout << std::endl;
}
    
void GradeCalc::sort(bool ascending) {
    if(ascending)
        std::sort(grades.begin(), grades.end());
    else
        std::sort(grades.begin(), grades.end(), std::greater<int>());
}

int GradeCalc::min() const {
    if(grades.empty())
        return -1;

    auto it = std::min_element(grades.begin(), grades.end());
    return *it;
}

int GradeCalc::max() const {
    if(grades.empty()) 
        return -1;

    auto it = std::max_element(grades.begin(), grades.end());
    return *it;
}

double GradeCalc::average() const {
    if(grades.empty())
        return 0.0;

    double avg = std::accumulate(grades.begin(), grades.end(), 0.0)/grades.size();
    return avg;
}

void GradeCalc::info() {
    if(is_dirty) 
       compute();

    std::cout << "课程名称:\t" << course_name << std::endl;
    std::cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << std::endl;
    std::cout << "最高分:\t" << max() << std::endl;
    std::cout << "最低分:\t" << min() << std::endl;

    const std::array<std::string, 5> grade_range{"[0, 60) ", 
                                           "[60, 70)", 
                                           "[70, 80)",
                                           "[80, 90)", 
                                           "[90, 100]"};
    
    for(int i = static_cast<int>(grade_range.size())-1; i >= 0; --i)
        std::cout << grade_range[i] << "\t: " << counts[i] << "人\t"
                  << std::fixed << std::setprecision(2) << rates[i]*100 << "%\n";
}

void GradeCalc::compute() {
    if(grades.empty())
        return;

    counts.fill(0); 
    rates.fill(0.0);

    for(auto grade:grades) {
        if(grade < 60)
            ++counts[0];
        else if (grade < 70)
            ++counts[1];
        else if (grade < 80)
            ++counts[2];
        else if (grade < 90)
            ++counts[3];
        else
            ++counts[4];
    }

    for(size_t i = 0; i < rates.size(); ++i)
        rates[i] = counts[i] * 1.0 / grades.size();
    
    is_dirty = false;
}

task1.cpp:

#include <iostream>
#include <string>
#include "GradeCalc.hpp"

void test() {
    GradeCalc c1("OOP");

    std::cout << "录入成绩:\n";
    c1.input(5);

    std::cout << "输出成绩:\n";
    c1.output();

    std::cout << "排序后成绩:\n";
    c1.sort(); c1.output();

    std::cout << "*************成绩统计信息*************\n";
    c1.info();

}

int main() {
    test();
}

运行结果截图:

任务1

问题1:

std::string course_name;功能是存储课程名

std::vector<int> grades;功能是存储课程成绩

std::array<int, 5> counts;功能是保存各分数段人数

std::array<double, 5> rates;功能是保存各分数段人数占比

bool is_dirty;功能是记录是否成绩信息有变更

问题2:

不合法,push_back()是vector里的成员函数,而vector的对象grades是类里的私有成员,外部不能用

问题3:

(1)compute调用1次,因为成绩信息未改变,if_dirty用于记录成绩信息是否有变更

(2)不需要,只要info函数中检测到if_dirty为true,则会调用compute

问题4:

{

if(grades.size()==1{

return grades[grades.size()/2];

{

else{

return (grades[grades.size()/2]+grades[grades.size()/2-1])/2;

}

}在info函数里加

问题5:

不能去掉,在进行多次成绩存储时会出现错误

问题6:

(1)对功能无影响,去掉后仍能运行

(2)对性能有影响,存储空间不足是会重新分配新内存,运行影响效率

 

 

实验任务2:

源代码:

GradeCalc.hpp:

#pragma once

#include <array>
#include <string>
#include <vector>

class GradeCalc: private std::vector<int> {
public:
    GradeCalc(const std::string &cname);      
    void input(int n);
    void output() const;
    void sort(bool ascending = false);
    int min() const;
    int max() const;
    double average() const;
    void info();

private:
    void compute();

private:
    std::string course_name;
    std::array<int, 5> counts;
    std::array<double, 5> rates;
    bool is_dirty;
};

GradeCalc.cpp:

#include <algorithm>
#include <array>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
#include "GradeCalc.hpp"


GradeCalc::GradeCalc(const std::string &cname): course_name{cname}, is_dirty{true}{
    counts.fill(0);
    rates.fill(0);
}   

void GradeCalc::input(int n) {
    if(n < 0) {
        std::cerr << "无效输入! 人数不能为负数\n";
        return;
    }

    this->reserve(n);

    int grade;

    for(int i = 0; i < n;) {
        std::cin >> grade;
        if(grade < 0 || grade > 100) {
            std::cerr << "无效输入! 分数须在[0,100]\n";
            continue;
        }

        this->push_back(grade);
        ++i;
    } 

    is_dirty = true;
}  

void GradeCalc::output() const {
    for(auto grade: *this)
        std::cout << grade << ' ';
    std::cout << std::endl;
} 

void GradeCalc::sort(bool ascending) {
    if(ascending)
        std::sort(this->begin(), this->end());
    else
        std::sort(this->begin(), this->end(), std::greater<int>());
}  

int GradeCalc::min() const {
    if(this->empty())
        return -1;

    return *std::min_element(this->begin(), this->end());
}  

int GradeCalc::max() const {
    if(this->empty())
        return -1;

    return *std::max_element(this->begin(), this->end());
}    

double GradeCalc::average() const {
    if(this->empty())
        return 0.0;

    double avg = std::accumulate(this->begin(), this->end(), 0.0) / this->size();
    return avg;
}   

void GradeCalc::info() {
    if(is_dirty) 
        compute();

    std::cout << "课程名称:\t" << course_name << std::endl;
    std::cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << std::endl;
    std::cout << "最高分:\t" << max() << std::endl;
    std::cout << "最低分:\t" << min() << std::endl;

    const std::array<std::string, 5> grade_range{"[0, 60) ", 
                                           "[60, 70)", 
                                           "[70, 80)",
                                           "[80, 90)", 
                                           "[90, 100]"};
    
    for(int i = static_cast<int>(grade_range.size())-1; i >= 0; --i)
        std::cout << grade_range[i] << "\t: " << counts[i] << "人\t"
                  << std::fixed << std::setprecision(2) << rates[i]*100 << "%\n";
}

void GradeCalc::compute() {
    if(this->empty())
        return;
    
    counts.fill(0);
    rates.fill(0);

    for(int grade: *this) {
        if(grade < 60)
            ++counts[0];
        else if (grade < 70)
            ++counts[1];
        else if (grade < 80)
            ++counts[2];
        else if (grade < 90)
            ++counts[3];
        else
            ++counts[4];
    }

    for(size_t i = 0; i < rates.size(); ++i)
        rates[i] = counts[i] * 1.0 / this->size();
    
    is_dirty = false;
}

task2.cpp:

#include <iostream>
#include <string>
#include "GradeCalc.hpp"

void test() {
    GradeCalc c1("OOP");

    std::cout << "录入成绩:\n";
    c1.input(5);

    std::cout << "输出成绩:\n";
    c1.output();

    std::cout << "排序后成绩:\n";
    c1.sort(); c1.output();

    std::cout << "*************成绩统计信息*************\n";
    c1.info();

}

int main() {
    test();
}

运行结果截图:

任务2

问题1:

class GradeCalc: private std::vector<int>{

问题2:

基类vector<int>的接口不会自动成为GradeCalc的接口

编译不能通过,因为是私有继承,所以push_back()不能在外部被访问

问题3:

组合方式通过grades接口访问数据

继承方式通过this访问数据

问题4:

组合方案更适合,组合的封装性更强,安全性高,且组合灵活性好,方便后续功能添加修改

 

 

实验任务3

源代码:

Graph.hpp:

#pragma once

#include <string>
#include <vector>

enum class GraphType {circle, triangle, rectangle};

class Graph {
public:
    virtual void draw() {}
    virtual ~Graph() = default;
};

class Circle : public Graph {
public:
    void draw();
};

class Triangle : public Graph {
public:
    void draw();
};

class Rectangle : public Graph {
public:
    void draw();
};

class Canvas {
public:
    void add(const std::string& type);
    void paint() const;
    ~Canvas();

private:
    std::vector<Graph*> graphs;          
};

GraphType str_to_GraphType(const std::string& s);
Graph* make_graph(const std::string& type);

Graph.cpp:

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

#include "Graph.hpp"

void Circle::draw()     { std::cout << "draw a circle...\n"; }

void Triangle::draw()   { std::cout << "draw a triangle...\n"; }

void Rectangle::draw()  { std::cout << "draw a rectangle...\n"; }

void Canvas::add(const std::string& type) {
    Graph* g = make_graph(type);
    if (g) 
        graphs.push_back(g);
}

void Canvas::paint() const {
    for (Graph* g : graphs) 
        g->draw();   
}

Canvas::~Canvas() {
    for (Graph* g : graphs) 
        delete g;
}

GraphType str_to_GraphType(const std::string& s) {
    std::string t = s;
    std::transform(s.begin(), s.end(), t.begin(),
                   [](unsigned char c) { return std::tolower(c);});

    if (t == "circle")   
        return GraphType::circle;

    if (t == "triangle") 
        return GraphType::triangle;

    if (t == "rectangle")
        return GraphType::rectangle;

    return GraphType::circle;
}

Graph* make_graph(const std::string& type) {
    switch (str_to_GraphType(type)) {
    case GraphType::circle:     return new Circle;
    case GraphType::triangle:   return new Triangle;
    case GraphType::rectangle:  return new Rectangle;
    default: return nullptr;
    }
}

task3.cpp:

#include <string>
#include "Graph.hpp"

void test() {
    Canvas canvas;

    canvas.add("circle");
    canvas.add("triangle");
    canvas.add("rectangle");
    canvas.paint();
}

int main() {
    test();
}

运行结果截图:

任务3

问题1:

(1)std::vector<Graph*> graphs;功能是存储图的指针

(2)class Circle : public Graph {

class Triangle : public Graph {

class Rectangle : public Graph {

问题2:

(1)会调用基类的draw而非子类的,没有输出

(2)调用draw()时只会执行基类的函数draw(),而不会执行子类的

(3)会导致子类折构不能进行

问题3:

Garph.hpp中声明Star类,枚举中增加star

Graph.cpp中增加Star::draw的实现,工具函数里也增加star对应的内容

task4.cpp中的test函数里增加canvas.add("star");

问题4:

(1)在析构函数中被释放

(2)利:简单,灵活性高

弊:需要手动分配内存

 

 

实验任务4

源代码:

Toy.hpp:

#pragma once

#include <iostream>
#include <string>
#include <vector>

class Toy {
public:
    Toy(std::string n,std::string t,std::string p,std::string c);
    void output();
    virtual void specialfunction();
    virtual ~Toy();
    
private:
    std::string name;
    std::string type;
    std::string price;
    std::string color;
};

class BrightToy:public Toy{
public:
    BrightToy(std::string n,std::string t,std::string p,std::string c,std::string b);
    void specialfunction();
    
private:
    std::string brightcolor;
};

class SoundToy:public Toy{
public:
    SoundToy(std::string n,std::string t,std::string p,std::string c,std::string s);
    void specialfunction();
    
private:
    std::string soundtype;
};

class MoveToy:public Toy{
public:
    MoveToy(std::string n,std::string t,std::string p,std::string c,std::string m);
    void specialfunction();
    
private:
    std::string movetype;
};

class ToyFactory{
public:
    ToyFactory(std::string n);
    void addToy(Toy* toy);
    void TFoutput();
    ~ToyFactory();
    
private:
    std::string factoryname;
    std::vector<Toy*> toys;
};

Toy.cpp:

#include "Toy.hpp"

Toy::Toy(std::string n,std::string t,std::string p,std::string c):name(n),type(t),price(p),color(c){}

void Toy::output(){
    std::cout<<"名称:"<<name<<"\n种类:"<<type<<"\n颜色:"<<color<<"\n价格:"<<price<<std::endl;
}

Toy::~Toy(){}

void Toy::specialfunction(){
    output();
}

BrightToy::BrightToy(std::string n,std::string t,std::string p,std::string c,std::string b):Toy(n,t,p,c),brightcolor(b){}

void BrightToy::specialfunction(){
    output();
    std::cout<<"特异功能:发出" <<brightcolor<<"的光"<<std::endl;
    std::cout<<std::endl;
}

SoundToy::SoundToy(std::string n,std::string t,std::string p,std::string c,std::string s):Toy(n,t,p,c),soundtype(s){}

void SoundToy::specialfunction(){
    output();
    std::cout<<"特异功能:发出" <<soundtype<<"的声音"<<std::endl;
    std::cout<<std::endl;
}

MoveToy::MoveToy(std::string n,std::string t,std::string p,std::string c,std::string m):Toy(n,t,p,c),movetype(m){}

void MoveToy::specialfunction(){
    output();
    std::cout<<"特异功能:做出" <<movetype<<"的动作"<<std::endl;
    std::cout<<std::endl;
}

ToyFactory::ToyFactory(std::string n):factoryname(n){}

void ToyFactory::addToy(Toy* toy){
    if(toy!=nullptr){
        toys.push_back(toy);
    }
}

void ToyFactory::TFoutput(){
    std::cout<<"************"<<factoryname<<"玩具信息************"<<std::endl;
    for(auto& toy:toys){
        toy->specialfunction();
    } 
}

ToyFactory::~ToyFactory(){
    for(auto toy:toys){
        delete toy;
    }
}

task4.cpp:

#include "Toy.hpp"

void test(){
    ToyFactory factory("南京玩具工厂");
    factory.addToy(new BrightToy("小猫","发光玩具","黄色","50元","白色"));
    factory.addToy(new SoundToy("鹦鹉","声音模仿玩具","红色","80元","小狗"));
    factory.addToy(new MoveToy("兔子","运动玩具","白色","90元","跳跃"));
    factory.addToy(new BrightToy("小狗","发光玩具","棕色","60元","黄色"));
    factory.TFoutput(); 
}

int main(){
    test();
    return 0;
}

运行结果截图:

任务4

 

posted @ 2025-11-29 20:44  系统警告  阅读(4)  评论(0)    收藏  举报