c++ - 类链中的转换

标签 c++ oop inheritance composition

我有一个对象 SSS0S1S2 层组成……就像一堆可堆叠的抽屉。

我想创建一个模板类链 A, B, C 这样:

  1. 它们代表 S 对象不同层的代理。
  2. 即使在模板实例化期间,C 也可以转换为 BB 可以转换为 A
  3. ABC 具有不同的方法集。

问题是,如果我使用公共(public)继承,那么 C 将获得 AB 的方法。

测试:

#include <iostream>
// Library
template <typename T>
class A {
public:
    void a() {std::cout << "a\n"; }
    int s_{0};
};

template <typename T>
class B : public A<T> {
public:
    void b() {std::cout << "b\n"; }
};

template <typename T>
class C : public B<T> {
public:
    void c() {std::cout << "c\n"; }
};

// User of library write a function like this
template <typename T>
void foo(A<T>& a) { a.a(); }

// The problem:
int main() {
    C<int> c;
    foo(c);
    c.a();  // <--- how to hide this?
    return 0;
}

最佳答案

我不确定我是否明白你想要什么。但一种方法是更改​​派生类中基类成员的访问级别。例如:

template <typename T>
class C : public B<T> {
public:
    void c() { std::cout << "c\n"; }
private:
    using A::a;  // <-- reduce access level of base class member
};

关于c++ - 类链中的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50281362/

相关文章:

c# - 将公共(public)属性/方法继承到 Asp.NET MVC 中的多个模型的最佳方法

inheritance - 扩展扩展有序的Scala类

c++ - 我的菱形继承(钻石问题)编译器错误无法解决?

c++ - 自定义异常类 - 奇怪的行为

c++ - 将宏传递给另一个宏而不是直接传递东西时出现不需要的额外 "empty"参数

c++ - 如何暂时抑制 printf 的输出?

python - 类中的函数实例变量

java - 面向对象的java样题考试

c++ - 列出 Windows 进程和模块

c# - 方法依赖 - 最佳实践?