火龙信奥
  • 首页
  • 课程
  • 题库
  • 打卡
    • 代码对战
    • 快速对战
  • 题单
  • 团队
  • 荣誉墙
  • 商城
  • 登录 / 注册

ws2425-02后面三大题代码

作者: 作者的头像   huolong , 时间:2025-09-15 15:01:25 , 所有人可见, 阅读  14

学习基类、派生类、多态概念,虚函数


#include <iostream>
#include <string>
using namespace std;

// 基类:银行账户
class Account {
protected:
    string accountNumber;  // 账户号码
    double balance;        // 账户余额
public:
    Account(string number) : accountNumber(number), balance(0) {}
    void deposit(double amount) {// 存款方法
        balance += amount;
        cout << "成功存入: " << amount << endl;
    }   
    // 纯虚函数:取款(强制子类实现)
    virtual void withdraw(double amount) = 0;

    // 显示账户信息
    virtual void display() const {
        cout << "账户[" << accountNumber << "] 余额: " << balance << endl;
    }
};

// 子类:活期账户(支持透支)
class CurrentAccount : public Account {
    double overdraftLimit;  // 透支额度

public:
    CurrentAccount(string number, double limit) 
        : Account(number), overdraftLimit(limit) {}

    // 实现取款(允许透支)
    void withdraw(double amount) override {
        if(amount <= balance + overdraftLimit) {
            balance -= amount;
            cout << "成功取出: " << amount << endl;
        } else {
            cout << "错误:超过透支限额!" << endl;
        }
    }

    // 显示活期账户特有信息
    void display() const override {
        Account::display();
        cout << "透支额度: " << overdraftLimit << endl;
    }
};

// 子类:储蓄账户(无透支)
class SavingsAccount : public Account {
public:
    SavingsAccount(string number) : Account(number) {}

    // 实现取款(不允许透支)
    void withdraw(double amount) override {
        if(amount <= balance) {
            balance -= amount;
            cout << "成功取出: " << amount << endl;
        } else {
            cout << "错误:余额不足!" << endl;
        }
    }
};

int main() {
    // 创建活期账户(透支额度1000)
    CurrentAccount myCurrent("CUR123", 1000);
    myCurrent.deposit(500);
    myCurrent.withdraw(1200);  // 允许透支
    myCurrent.display();

    // 创建储蓄账户
    SavingsAccount mySavings("SAV456");
    mySavings.deposit(300);
    mySavings.withdraw(400);   // 将拒绝
    mySavings.display();

    return 0;
}

设计题、三角形、矩形


#include <iostream>
#include <string>
using namespace std;

class GeometrischeForm {
public:
    virtual double berechneFlaeche() const = 0; // 纯虚函数
    virtual void ausgabe() const { 
        cout << "Allgemeine Form" << endl; 
    }
    virtual ~GeometrischeForm() = default;
};

class Kreis : public GeometrischeForm {
    double radius;
public:
    Kreis(double r) : radius(r) {}
    double berechneFlaeche() const override {
        return 3.14159 * radius * radius;
    }
    void ausgabe() const override {
        cout << "Kreis mit Radius: " << radius << endl;
    }
};

class Rechteck : public GeometrischeForm {
    double breite, hoehe;
public:
    Rechteck(double b, double h) : breite(b), hoehe(h) {}
    double berechneFlaeche() const override {
        return breite * hoehe;
    }
    void ausgabe() const override {
        cout << "Rechteck " << breite << "x" << hoehe << endl;
    }
};

int main() {
    GeometrischeForm* formen[] = {
        new Kreis(5.0),
        new Rechteck(4.0, 6.0)
    };

    for (auto* form : formen) {
        form->ausgabe();
        cout << "Flaeche: " << form->berechneFlaeche() << endl;
        delete form;
    }

    return 0;
}

二叉搜索树


#include <iostream>
using namespace std;

class BinTree {
private:
    struct Node {
        int data;
        Node *left, *right;
        Node(int val) : data(val), left(nullptr), right(nullptr) {}
    } *root;

    Node* insert(Node* node, int value) {
        if (!node) return new Node(value);
        if (value < node->data) {
            node->left = insert(node->left, value);
        } else {
            node->right = insert(node->right, value);
        }
        return node;
    }

    int depthFactorSum(Node* node, int depth) {
        if (!node) return 0;
        return node->data * depth + 
               depthFactorSum(node->left, depth + 1) + 
               depthFactorSum(node->right, depth + 1);
    }

    void clear(Node* node) {
        if (node) {
            clear(node->left);
            clear(node->right);
            delete node;
        }
    }

public:
    BinTree() : root(nullptr) {}
    ~BinTree() { clear(root); }

    void insert(int value) {
        root = insert(root, value);
    }

    int depthFactorSum() {
        return depthFactorSum(root, 0);
    }
};

int main() {
    BinTree tree;
    tree.insert(5);
    tree.insert(3);
    tree.insert(8);
    tree.insert(2);
    tree.insert(4);
    tree.insert(10);

    cout << "Depth Factor Sum: " << tree.depthFactorSum() << endl;
    return 0;
}

看程序输出结果


#include <iostream>
#include <string>
#include <deque>

using namespace std;

// 抽象基类GeomForm
class GeomForm {
protected:
    double x, y;

public:
    GeomForm(double x_, double y_) : x(x_), y(y_) {}

    double getX() const { return x; }
    double getY() const { return y; }

    virtual double getArea() const = 0;
    virtual string getDesc() const { return "Ich bin eine Form"; }
};

// 派生类Rectangle
class Rectangle : public GeomForm {
private:
    double width, height;

public:
    Rectangle(double x_, double y_, double w_, double h_) 
        : GeomForm(x_, y_), width(w_), height(h_) {}

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

    string getDesc() const override {
        return "Ich bin ein Rechteck";
    }
};

// 派生类Triangle
class Triangle : public GeomForm {
private:
    double m_height;
    double m_base;

public:
    Triangle(double x, double y, double height, double base)
        : GeomForm(x, y), m_height(height), m_base(base) {}

    string getDesc() const override {
        return "Ich bin ein Dreieck";
    }

    double getArea() const override {
        return m_height * m_base / 2;
    }
};

int main() {
    deque<GeomForm*> list;

    list.push_back(new Rectangle(1.0, 2.0, 3.0, 3.0));
    list.push_back(new Triangle(4.0, 4.0, 4.0, 4.0));
    list.push_back(new Triangle(1.5, 3.0, 1.0, 3.0));
    list.push_back(new Rectangle(1.5, 3.0, 1.0, 1.0));

    int i = 1;
    for (GeomForm *form : list) {
        cout << i << ": " << form->getDesc() << ", A=";
        cout << form->getArea() << endl;
        i++;
    }

    // 释放内存
    for (GeomForm *form : list) {
        delete form;
    }

    return 0;
}

改成模板

#include <iostream>
#include <string>
using namespace std;

template<typename A, typename B>
class Summentyp {
public:
    // 构造函数
    Summentyp() : value(nullptr), type(0) {}

    Summentyp(const A& val) : value(nullptr), type(0) {
        setValue(val);
    }

    Summentyp(const B& val) : value(nullptr), type(0) {
        setValue(val);
    }

    // 获取 A 类型的值指针(如果当前是 A)
    A* getValueA() const {
        if (type == 'A') {
            return static_cast<A*>(value);
        }
        return nullptr;
    }

    // 获取 B 类型的值指针(如果当前是 B)
    B* getValueB() const {
        if (type == 'B') {
            return static_cast<B*>(value);
        }
        return nullptr;
    }

    // 设置为 A 类型的值
    void setValue(const A& val) {
        deleteValue();                // 先清理旧值
        value = new A(val);           // 动态分配 A
        type = 'A';
    }

    // 设置为 B 类型的值
    void setValue(const B& val) {
        deleteValue();                // 先清理旧值
        value = new B(val);           // 动态分配 B
        type = 'B';
    }

    // 返回当前类型标识
    char getVariante() const {
        return type;
    }

    // 清理当前存储的值
    void deleteValue() {
        switch (type) {
            case 'A':
                delete static_cast<A*>(value);
                break;
            case 'B':
                delete static_cast<B*>(value);
                break;
            default:
                break;
        }
        value = nullptr;
        type = 0;
    }

    // 析构函数
    ~Summentyp() {
        deleteValue();
    }

private:
    void* value;   // 指向 A 或 B 类型对象的指针
    char type;     // 'A' = 当前是 A 类型, 'B' = 当前是 B 类型, 0 = 空
};


int main() {
    Summentyp<char, const char*> summentyp;
    summentyp.setValue("Hallo");
    summentyp.setValue('!');
    cout << "Wert: " << *summentyp.getValueA() << endl;
    return 0;
}

异常处理

#include <iostream>
using namespace std;

// 共同的异常基类
class BaseException {
public:
    virtual void printError() const = 0;  // 纯虚函数,输出错误信息
    virtual ~BaseException() {}           // 虚析构函数
};

// 空数组异常
class EmptyArrayException : public BaseException {
public:
    void printError() const override {
        cerr << "Fehler: Arraygroesse 0" << endl;
    }
};

// 无效值异常
class InvalidValueException : public BaseException {
private:
    int invalidValue;  // 存储导致错误的无效值
public:
    InvalidValueException(int value) : invalidValue(value) {}

    void printError() const override {
        cerr << "Fehler: Array enthaelt ungueltigen Wert " << invalidValue << endl;
    }
};

// 修改后的 berechneWerte:不再返回错误码,而是抛出异常
void berechneWerte(int* werte, unsigned int const n) {
    if (n == 0) {
        throw EmptyArrayException();  // 错误码 1 -> 抛出异常
    }

    for (unsigned int i = 0; i < n; ++i) {
        if (werte[i] < 0 || werte[i] > 2047) {
            throw InvalidValueException(werte[i]);  // 错误码 2 -> 抛出带值的异常
        }
        werte[i] *= (werte[i] + 1);  // 执行计算
    }
}

// 主函数
int main() {
    int const n = 4;
    int werte[n] = { 2, 1, -2, 0 };  // 包含 -2,是非法值

    try {
        berechneWerte(werte, n);

        // 如果没有异常,则输出结果
        for (unsigned int i = 0; i < n; ++i) {
            cout << werte[i] << endl;
        }

    } catch (const BaseException& e) {
        e.printError();  // 多态调用具体异常的 printError()
    }

    return 0;
}

—— 本文来自火龙信奥(义乌睿码科技):义乌青少年信息学奥赛与编程教育平台,专注 CSP-J/S、NOIP、GESP 竞赛培训,线上线下融合教学,助力编程升学。网址:hlcoding.com

©2026加盟我们 | 关于我们 | ACM课程 | 常见问题 | 成果墙 | 评测记录 | 浙ICP备2021013995号
在线画图 | OI WIki | 打字练习
火龙信奥
请输入登录信息


请完成安全验证
验证码底图 滑块
向右拖动滑块完成验证
请输入用户名 / 绑定的手机号码



请输入注册信息(手机号验证码注册)





验证码5分钟有效,60秒内不可重复获取,每日最多3次

微信登录

微信登录二维码

正在生成二维码...

账号已过期,请续期。
去续期

绑定手机号

📱

为了更好地保护您的账号安全,享受完整的平台服务

请您尽快绑定手机号码