无法在派生类中定义嵌套类成员函数

Cannot define nested class member function within derived class

本文关键字:嵌套 成员 函数 定义 派生      更新时间:2023-10-16

我有一个由另一个类组成的基类(我们称之为组件)。 如果我从基类继承,是否可以向组件类添加功能(假设您无法修改基代码)? 我基本上想要一个"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 下给出以下错误:

错误:无法在"派生"中定义成员函数"Base::Component::foo"

[..] 添加功能 [..] (假设您无法修改基本代码) [..]

根据所讨论的实际基类的外观,您可以尝试使用Component的简单子类化:

/* 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必须具有虚拟析构函数。

您需要

Component类中声明foo函数。然后在Component本身中定义它:

#include <iostream>
class Base
{
public:
    void Print() { std::cout << c.data; }
    class Component
    {   
    public:
        int data;
        void foo( int value )
        { 
            data = value; 
        }
    };  
    Component c;
};
class Derived : public Base
{
private:
public:
    void bar(int value)
    {   
        c.foo(value);
    }   
};
int main() {
    Derived d;
    d.bar(4);
    d.Print();
}

或在所有类之外:

#include <iostream>
class Base
{
public:
    void Print() { std::cout << c.data; }
    class Component
    {   
    public:
        int data;
        void foo( int value );
    };  
    Component c;
};
void Base::Component::foo(int value) 
{ 
    data = value; 
}
class Derived : public Base
{
private:
public:
    void bar(int value)
    {   
        c.foo(value);
    }   
};
int main() {
    Derived d;
    d.bar(4);
    d.Print();
}