构造函数主体中的对象初始化
Object initialization in constructor body
我已经编写了一个类来根据模式执行存储在unordered_map
中的数据的输出。我希望这个模式在创建时传递给对象,并且在对象生命周期内保持不变。
这是我第一次写的课:
class Format {
public:
Format(const string output_pattern);
string interpolate(const boost::unordered_map<string, string> & field_values);
private:
...
};
我想以这种方式在另一个类中使用Formatter
:
class A {
private:
Format formatter;
public:
A(const std::map<std::string, std::string> & info, ... other parameters) {
std::map<std::string, std::string>::const_iterator it;
it = info.find("format");
if (it == info.end()) {
throw std::runtime_error("Can't find 'format' in info");
} else {
formatter = Format(it->second);
}
}
};
正如您所看到的,在调用构造函数之前还有一些工作要做。毫无疑问,它不起作用,因为format
首先是用默认构造函数初始化的(缺少默认构造函数),其次它需要为formatter = Format(it->second);
行定义赋值运算符。
我不能像这样初始化formatter
:
A(const std::map<std::string, std::string> & info, ... other parameters):
formatter(...) {
...
}
因为我必须首先提取要作为formatter
初始值设定项传递的参数。
所以,最终我用这种方式解决了这个问题:
class Format {
public:
Format();
void set_pattern(const string output_pattern);
string interpolate(const boost::unordered_map<string, string> & field_values);
private:
...
};
class A {
private:
Format formatter;
public:
A(const std::map<std::string, std::string> & info, ... other parameters):
formatter()
{
std::map<std::string, std::string>::const_iterator it;
it = info.find("format");
if (it == info.end()) {
throw std::runtime_error("Can't find 'format' in info");
} else {
formatter.set_pattern(it->second);
}
}
};
我真正不喜欢的是,这将不可变的formatter
对象变成了可变的。这不是什么大问题。但我不需要它是可变的,也不喜欢因为它是不可变的,我不能用代码来表达它而必须使它可变。
在我的情况下,有没有其他好的方法可以在构造函数中初始化它?
您可以使用助手专用函数来完成实际工作:
class A {
private:
SomethingA before;
Format formatter;
SomethingB after;
public:
A(const std::map<std::string, std::string>& info) :
formatter(extractFormat(info))
{
// ...
}
private:
string extractFormat(const std::map<std::string, std::string>& info)
{
// Be careful here! The object is not constructed yet, you can't fully use it
// this->before => ok
// this->after => not ok
// you could make this function static just to be safe
}
};
相关文章:
- 用C++中的CPerson(类)类型的对象初始化STL矢量
- 对象初始化中是否允许指向此成员的指针?
- 对象初始化后在C++中显示 char 数组时的异常行为
- 为什么两种不同的对象初始化方式给出不同的输出
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- afxmem.cpp中的对象初始化差异
- 删除通过取消引用新对象初始化的对象
- 如何使用sregex_token_iterator对象初始化向量
- 关于默认构造函数,对象初始化/使用C++ OOP
- C++ 基元类型初始化与对象初始化
- 哪个函数负责C++全局范围内的类对象初始化?
- C++中构造函数的对象初始化出现问题
- 如何修复模板 BST 类的对象初始化
- 无法在 QML/C++ 中使用绑定对象初始化 UI
- 为什么参数可以在对象初始化时通过赋值运算符传递给构造函数?
- 类对象初始化的二维向量
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- 对象初始化
- 类对象初始化
- 使用从另一个类继承的类的对象初始化成员对象