我知道在C ++ 11中,构造函数委托可以像这样:
class Foo
{
public:
Foo()
{
// Some code to be ran first
}
Foo(std::string bar): Foo() // Runs the code to be ran first
{
// Some code to be ran second, presumably using bar
}
};
我想知道如何以某种方式扭转这种局面。即,在调用Foo()
构造函数的情况下,我想运行一些代码来找出std::string
的值,然后Foo(std::string bar)
将使用该值完成初始化。因此,Foo()
既运行自己的代码,又运行Foo(std::string bar)
中的代码,而后者仅运行自己的代码,例如
class Foo
{
public:
Foo()
{
std::string bar_figured_out;
// Figures out the value for bar_figured_out
Foo(bar_figured_out); // I know this wouldn't work, just an example of what I'm trying to do.
}
Foo(std::string bar):
{
// Some code to finish class initialization, using bar
}
};
可以使用构造函数委托来完成此操作吗?
您有两个选择:
将代码从Foo(std::string bar)
移动到成员函数,并从Foo()
和Foo(std::string bar)
都调用它。
将确定bar_figured_out
值的代码移至成员函数,然后在委派给Foo()
时让Foo(std::string bar)
调用该函数:
Foo() : Foo(compute_bar()) {}