无法在派生类中定义嵌套类成员函数
Cannot define nested class member function within derived class
我有一个由另一个类组成的基类(我们称之为组件)。 如果我从基类继承,是否可以向组件类添加功能(假设您无法修改基代码)? 我基本上想要一个"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();
}
相关文章:
- 嵌套在类中时无法设置成员数据
- 如何在 C++ 的外部类构造函数中初始化嵌套类成员
- 迭代嵌套映射与范围为循环:没有名为"first"的成员
- 如何从另一个嵌套类中调用某个封闭类的嵌套类的函数指针成员的值?
- MSVC 2017 - 错误 - 如何将模板类 X 的模板成员函数声明为嵌套类 X::Y 的好友
- std::void_t 和嵌套的非类型成员
- C2436 '{ctor}':构造函数初始值设定项列表中的成员函数或嵌套类
- c++ 嵌套结构映射找不到成员
- 无法从多态嵌套类访问包含类的成员
- 其他类的成员函数对成员函数的嵌套引用
- 如何从嵌套在命名空间中的类调用成员函数?
- 返回自身内部的双重嵌套类的成员函数,该类继承自从自身继承的类
- 嵌套的类成员变量不可访问.链表设置.V、下一个和新的问题
- 当使用嵌套类功能时,使用非静态数据成员的使用无效,但是当函数未固定时可以
- 包含指针成员的嵌套结构
- 缩短成员函数作用域说明符(嵌套类)(C++)
- 为什么嵌套类的成员函数不需要完整类型?
- 使用泛型函数调用打印结构的所有嵌套成员变量
- 嵌套成员类型识别
- 初始化构造函数中嵌套成员的语法