【发布时间】:2018-12-09 14:28:33
【问题描述】:
我决定使用builder 模式来避免长的未命名参数构造函数,但我有一个特定的用例。我有一个基类和一些从中继承的类,它们都必须能够单独构建。下面显示一个伪代码解释我的特殊用例:
class B
{
int i;
int j;
public:
B& setI(int i) {this->i=i; return *this;}
B& setJ(int j) {this->j=j; return *this;}
}
class I : public B
{
int i2;
int j2;
public:
I& setI2(int i) {this->i2=i; return *this;}
I& setJ2(int j) {this->j2=j; return *this;}
}
B b = B().setI(12).setJ(13); // ok
I i = I().setI(12).setJ(13).setI2(14).setJ2(15); // error the first and second function return B not I
上面的代码无法编译,因为B中的函数没有返回类I的类型。this post已经提出了解决方案,但是有限,不能单独创建基类。 我使用的是 c++11,但可以使用其他版本的 c++。
更新:
有一个解决方案是接受 B 作为 I 的构造函数的参数,但在实际问题中存在一些继承层,使用此解决方案不太实用。
【问题讨论】:
标签: c++ c++11 design-patterns