一系列课程中的转换

时间:2018-05-10 20:54:31

标签: c++ oop inheritance composition

我有一个对象SS由图层S0S1S2组成......就像一叠可堆叠的抽屉一样。

我想创建一系列模板类ABC,以便:

  1. 它们代表S对象的不同层的代理。
  2. 即使在模板实例化期间,C也可以转换为B,可以转换为A
  3. ABC有不同的方法集。
  4. 问题在于,如果我使用公共继承,那么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;
    }
    

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解你想要的东西。但是,一种方法是更改​​派生类中基类成员的访问级别。例如:

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
};