我有一个我想在其上使用构建器模式的类,但它派生自一个我需要访问其属性的基类。我无法BaseClass
在不公开的情况下访问我的实现中的成员,即使我从 BuilderBaseClass
或同样臭的东西派生。我的课程:
基类.h:
class BaseClass
{
protected:
CString name;
}
派生类.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;
};
派生类.cpp:
DerivedClass::DerivedClass(Builder builder)
{
this->name = builder.name; // this is NOT ok
this->description = builder.description; // this is ok
}
我的问题是我无法访问builder.name
。Visual Studio 说“受保护BaseClass::name
的成员不能通过DerivedClass::Builder
指针或对象访问”。我试过摆弄Builder
a friend
of BaseClass
,但无济于事。这篇文章也提供了一种解决方法,但它是针对 Java 的,而且非常混乱。
有没有一种体面的方法可以在 C++ 中使用具有继承的构建器模式?