#include #include #include

class ins { private: std::string name; std::function<int(int)> run;

public: static std::map<std::string, ins*> ins_map;

ins(std::string n, std::function<int(int)> r) : name(n), run(r) {
    ins_map[name] = this;
}

ins(const ins& other) : name(other.name), run(other.run) {
    ins_map[name] = this;
}

ins& operator=(const ins& other) {
    if (this != &other) {
        name = other.name;
        run = other.run;
        ins_map[name] = this;
    }
    return *this;
}

int execute(int value) {
    return run(value);
}

};

std::map<std::string, ins*> ins::ins_map;

int main() { // 创建一个 ins 对象并添加到 ins_map 中 ins obj1("obj1", [](int value) { return value * 2; });

// 复制构造一个新的 ins 对象,并添加到 ins_map 中
ins obj2 = obj1;

// 使用等号重载将 obj2 的值赋给 obj3,并更新 ins_map 中的映射
ins obj3("obj3", [](int value) { return value + 10; });
obj3 = obj2;

// 从 ins_map 中执行 obj1、obj2 和 obj3 的函数
std::cout << obj1.execute(5) << std::endl;  // 输出:10
std::cout << obj2.execute(5) << std::endl;  // 输出:10
std::cout << obj3.execute(5) << std::endl;  // 输出:10

return 0;

}

C++ 类 ins:包含构造函数、复制构造函数和等号重载,并使用 map 存储对象

原文地址: https://www.cveoy.top/t/topic/pZcg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录