从Child
的构造函数调用Parent
的构造函数时,如何首先基于下面的myString实例化AnotherClass
实例,然后将该AnotherClass
实例传递给Parent
的构造函数?如果这不可能,在C++中实现这一点的常见模式是什么?
class Parent {
public Parent(AnotherClass myClass){
//....
}
}
class Child : public Parent{
public Child (std::string myString) : Parent (// get a AnotherClass instance by passing in myString and use that instance as input to Parent constructor) {}
}
class AnotherClass{
public AnotherClass(std::string myString){
///
}
}
简单的解决方案:什么都不做。只要它不是AnotherClass:的显式ctor,编译器就会为您做这件事(如注释中所写(
class Child : public Parent
{
public Child(std::string myString)
: Parent(myString) {}
};
您甚至可以考虑简单地使用Parent
的ctor(通过简单地编写using Parent::Parent
(,尽管这会更改接口。
如果你想说得详细一点,你可以说(再次,就像在评论中一样(:
class Child : public Parent
{
public Child(std::string myString)
: Parent(AnotherClass(myString)) {}
};
这些都是针对简单的案例。然而,有时在调用Parent
的ctor之前,您需要解决一个更复杂的问题:例如,您想重用AnotherClass
或对其进行一些计算/验证。这就是我写下答案的原因:在一般情况下,您可能需要进行一些任意的复杂计算。在lambdas(或静态成员函数,甚至自由函数(的帮助下,您仍然可以这样做:
class Child : public Parent
{
public Child(std::string myString)
: Parent([&](){
// here you can write any code
// it'll run _before_ Parent's ctor
AnotherClass ac(myString);
// do any calculation on ac, store it, etc.
return ac;
}()) {}
};
此外,建议在传递参数时使用std::move
(当然,除非在ctor中的另一个位置也需要它(。