gpt4 book ai didi

成员参数的c++运行时实例化

转载 作者:行者123 更新时间:2023-11-28 07:01:28 25 4
gpt4 key购买 nike

正如标题所说,我想启动一个 Store 对象,其类型仅在运行时确定。我最初选择了一个虚拟类、2 个派生类,但很快就遇到了对模板的需求。

O 类有一个指向这些 Store 对象的接口(interface) BaseStore 的指针。此外,由于我还需要为派生类 Store1Store2 调用正确的函数,因此我在接口(interface)的模板函数中使用了动态转换。

由于本人是c++新手,不知道这样的设计有没有缺陷,有没有可以改进的地方。感谢您的专业知识!

#include <iostream>
using namespace std;

struct BaseStore {
virtual ~BaseStore() {}
template<typename S> void test() const;
};

struct Store1 : public BaseStore {
Store1(int j) { this->i = j; }
void test() const { cout << i << endl; }
private:
int i = 1;
};

struct Store2 : public BaseStore {
Store2(string s) { this->i = s; }
void test() const { cout << i << endl; }
private:
string i = "2";
};

template<typename S> void BaseStore::test() const
{
dynamic_cast<const S&>(*this).test();
}

class O {
public:
O(int i) {
this->type = i;
switch (this->type) {
case 1: basestore = new Store1(42); break;
case 2: basestore = new Store2("lol"); break;
}
}
~O() { delete basestore; }
void test() const {
switch (this->type) {
case 1: basestore->test<Store1>(); break;
case 2: basestore->test<Store2>(); break;
}
}
private:
int type;
BaseStore* basestore;
};

最佳答案

我相信虚函数和工厂模式会有所帮助,如:

struct BaseStore
{
virtual ~BaseStore() = default;
virtual void test() const = 0;

BaseStore() = default;
BaseStore(BaseStore const&) = delete;
BaseStore(BaseStore&&) = delete;
BaseStore& operator=(BaseStore&&) = delete;
BaseStore& operator=(BaseStore const&) = delete;

};

struct Store1 : public BaseStore {
Store1(int j) : i(j) {}
void test() const override { std::cout << i << std::endl; }
private:
int i = 1;
};

struct Store2 : public BaseStore {
Store2(std::string s) : i(std::move(s)) {}
void test() const override { std::cout << i << std::endl; }
private:
std::string i = "2";
};

class O {
public:
O(int i) : type(i), basestore(StoreFactory(i)) {}
void test() const { basestore->test(); }

private:

static std::unique_ptr<BaseStore> StoreFactory(int i)
{
switch (i)
{
case 1: return std::unique_ptr<Store1>(new Store1(42));
case 2: return std::unique_ptr<Store2>(new Store2("lol"));
default: throw std::runtime_error("Don't know what kind of Store you want");
}
}

int type;
std::unique_ptr<BaseStore> basestore;
};

关于成员参数的c++运行时实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22411292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com