对象初始化
Objects initialization
我想用C++构建一个框架,而C++没有内置的类似C#的反射特性是一个困难。
我试图解决的问题是:我有一个对象,我会在运行时知道它的类的名称(作为字符串),在运行时也会知道它的属性的名称(以字符串)。然后我想知道在运行时创建这个类的实例并在其属性中放入默认值而不必创建另一个构造函数的最佳方法是什么。
此外,我希望避免使用第三方库,如boost和编译器特定的功能。
感谢您的帮助,任何提示/想法都将不胜感激!
在纯标准C++中是不可能的(在运行时根据类的名称实例化),因为C++11没有反射。
然而,你可以考虑像这样的东西
- 添加您自己的元对象协议,就像Qt一样(参见其
moc
) - 有自己的惯例并使用X宏技巧
- 自定义您的C++编译器,例如,如果使用GCC扩展MELT
- 使用工厂设计模式结合动态链接àla dlopen(3)
我建议在您的框架中定义一些约定,并实现工具,以满足您的需求。例如,您可以定义自己的根类,并添加C++代码生成器(如Qt中的moc
)来帮助您。
还可以研究像Poco(当然还有Qt)这样的框架。
它很简单:
#include <string>
using namespace std;
class Blog
{
public:
Blog(string t, string d) : title(t), description(d) {}
string getTitle() {return title;}
void setTitle(string t) {title = t;}
// etc...
private:
string title;
string description;
}
然后启动
Blog *blog = new Blog {"The Title", "Blog description"};
class Blog
{
public:
Blog() {}
Blog(std::string s1, std::string s2): Title(s1), Description(s2){}
// add get, set methods separately as required
// alternately, you may declare Title, Description as public:
private:
std::string Title;
std::string Description;
}
...Then we use it somewhere
Blog blog = new Blog("The Title", "Blog description");
相关文章:
- C++使用整数的压缩数组初始化对象
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 在 c++ 中初始化对象
- C++ 手动分配和初始化对象
- 使用运算符"="在C++中用值初始化对象
- 当我不需要数据库中的所有值时,如何部分初始化 c++ 对象?
- 如何初始化对象数组?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- 如何在线程中初始化对象,然后在其他地方使用它?
- 在没有默认构造函数时使用垃圾数据初始化对象
- 如果在 C++ 构造函数中以错误的顺序初始化对象数据,会发生什么类型的错误
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 在 c++ 中复制对未初始化对象的引用
- 在成员变量在另一个文件中发生更改后,调用与初始化对象分开的函数
- 在不放置新运算符的情况下,在预分配的内存上使用虚函数初始化对象 - 这可能吗?如果没有,为什么
- 复制 CTOR 与赋值运算符以初始化对象(性能)
- 当您通过分配初始化C 对象时会发生什么
- 获取未初始化对象成员的地址是否定义良好?