我有一个由另一个类组成的基类(我们称它为组件)。如果我从 Base 类继承,是否可以向 Component 类添加功能(假设您不能修改 Base 代码)?我基本上想要一个“Derived::Component::foo”函数。
#include <iostream>
class Base
{
public:
void Print() { std::cout << c.data; }
class Component
{
public:
int data;
};
Component c;
};
class Derived : public Base
{
private:
void Component::foo(int value)
{
this->data = value;
}
public:
void bar(int value)
{
this->c.foo(value);
}
};
int main() {
Derived d;
d.bar(4);
d.Print();
}
此代码在 Ubuntu 上的 G++ 4.8 下出现以下错误:
错误:无法在“Derived”中定义成员函数“Base::Component::foo”
最佳答案
[..] add functionality [..] (assumming you can't modify the Base code) [..]
根据所讨论的实际基类的样子,您可以尝试通过 Component
的简单子(monad)类化来解决问题:
/* using struct to have public accessibility */
struct Base {
struct Component {
int data;
virtual ~Component() {} // ABSOLUTELY NECESSARY
};
std::unique_ptr<Component> component; // ABSOLUTELY NECESSARY
void print(void) {
std::cout << component->data << endl;
}
};
/* The decorated component, with the additional functionality */
struct DecoratedComponent : public Base::Component {
void set(int d) {
data = d;
}
};
然后,假设有某种方法可以设置组件,您需要传入装饰组件(注意:如果要保留状态,您还可以在装饰组件类中包装一个 Component
实例,使它成为装饰器模式的真正用法):
Base the_base;
auto the_component = std::make_unique<DecoratedComponent>();
// Inject the decorated component
the_base.component = the_component;
the_component.set(42);
the_base.print(); // 42
这仅在基使用引用或某种指针来存储/访问其组件时才有效。此外,如果基管理组件的生命周期,Component
必须有一个虚拟析构函数。
关于c++ - 无法在派生类中定义嵌套类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37472800/