我有一个类想要使用生成器模式,但它是从一个基类派生出来的,我需要访问基类的属性。如果我从BaseClass
继承Builder或者其他不太好的方式,我就无法在实现中访问BaseClass
的成员,即使我将它们设置为public也不行。我的类:
BaseClass.h:
class BaseClass
{
protected:
CString name;
}
DerivedClass.h:
class DerivedClass : public BaseClass
{
public:
// builder starts here and has the same base class as the class it is nested in
// (if it doesn't, we can't get access to name)
static class Builder : public BaseClass
{
public:
Builder::Builder(CString pName)
{
this->name = pName;
}
Builder Builder::Description(CString pDescription)
{
this->description = pDescription;
return *this;
}
};
public:
CString description;
};
DerivedClass.cpp:
DerivedClass::DerivedClass(Builder builder)
{
this->name = builder.name; // this is NOT ok
this->description = builder.description; // this is ok
}
我的问题是我无法访问
builder.name
。Visual Studio显示“protected member BaseClass::name
is not accessible through a DerivedClass::Builder
pointer or object”。我尝试了一些方法,比如将Builder
设为BaseClass
的friend
,但没有成功。这篇文章提供了一个解决方法,但是它是针对Java的,而且很混乱。有没有一种合理的方式在C++中使用继承与构建器模式?