实验3

一、实验结论

1. 实验任务1

程序源代码

button.hpp

#pragma once
#include <iostream>
#include <string>

class Button {
public:
    Button(const std::string &label_);
    const std::string& get_label() const;
    void click();
private:
    std::string label;
};

Button::Button(const std::string &label_): label{label_} {}

window.hpp

#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include "button.hpp"

class Window {
public:
    Window(const std::string &title_);
    void display() const;
    void close();
    void add_button(const std::string &label);
    void click_button(const std::string &label);
private:
    bool has_button(const std::string &label) const;
private:
    std::string title;
    std::vector<Button> buttons;
};

inline const std::string& Button::get_label() const {
    return label;
}

inline void Button::click() {
    std::cout << "Button '" << label << "' clicked\n";
}

Window::Window(const std::string &title_): title{title_} {
    buttons.push_back(Button("close"));
}

inline void Window::display() const {
    std::string s(40, '*');
    std::cout << s << std::endl;
    std::cout << "window : " << title << std::endl;
    int cnt = 0;
    for(const auto &button: buttons)
        std::cout << ++cnt << ". " << button.get_label() << std::endl;
    std::cout << s << std::endl;
}

inline void Window::close() {
    std::cout << "close window '" << title << "'" << std::endl;
    click_button("close");
}

inline bool Window::has_button(const std::string &label) const {
    for(const auto &button: buttons)
        if(button.get_label() == label)
            return true;
    return false;
}

inline void Window::add_button(const std::string &label) {
    if(has_button(label))
        std::cout << "button " << label << " already exists!\n";
    else
        buttons.push_back(Button(label));
}

inline void Window::click_button(const std::string &label) {
    for(auto &button:buttons)
        if(button.get_label() == label) {
            button.click();
            return;
        }
    std::cout << "no button: " << label << std::endl;
}

task1.cpp

#include "window.hpp"
#include <iostream>

void test(){
    Window w("Demo");
    w.add_button("add");
    w.add_button("remove");
    w.add_button("modify");
    w.add_button("add");
    w.display();
    w.close();
}

int main() {
    std::cout << "用组合类模拟简单GUI:\n";
    test();
}

运行测试截图

1

问题1:这个范例中, Window 和 Button 是组合关系吗?

是。Window类包含vector

posted @ 2025-11-26 07:29  isaacsun18  阅读(0)  评论(0)    收藏  举报