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

时间:2016-05-26 23:54:56

标签: c++ inheritance composition

我有一个由另一个类组成的Base类(我们称之为Component)。如果我从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'

2 个答案:

答案 0 :(得分:2)

  

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

根据所讨论的实际基类的样子,您可以尝试使用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实例在您的装饰组件类中,使其成为Decorator模式的真实用法:

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

这只有在base使用引用或某种指针来存储/访问它的组件时才有效。此外,如果基础管理组件的生命周期,Component必须具有虚拟析构函数。

答案 1 :(得分:1)

您需要在foo类中声明Component函数。然后在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();
}