c++ - 家长访问 child 私有(private)/ protected

标签 c++ templates polymorphism

是否有可能以某种方式允许 parent 访问受 child 保护的成员?

template <class T>
class B {
public :
    void print()
    {
        cout << T::a << T::b << endl;
    }
};

class C : public B<C>
{
protected :
    static int a;
    static int b;
public :
    C() {
        print();
    }
};

这对我在没有多态性(虚拟)的情况下继承多个对象很有用。有什么建议吗??

编辑:

我找到了下面建议的两个解决方案::

  • 将B作为 friend 类,
  • CRTP

还有几点需要考虑,在使用 CRTP 时确保您使用内联,否则它不会使其更快(但可能会发生代码膨胀)。不要忘记使 B 构造函数 protected (在静态派生数据访问的情况下)。

CRTP也可以用于不从基类向派生类传递静态常量数据(virtual static const)

现代编译器使用一个称为去虚拟化的概念,我认为现在大多数编译器中都有。

最佳答案

This will be useful for me to inherit multiple objects without polymorphism(virtual).

这是一个众所周知的模式,又名静态多态性

CRTP使用 static_cast<T*>(this)通常引用派生类函数:

template <class T>
class B {
public :
    void print()
    {
        cout << static_cast<T*>(this)->a << static_cast<T*>(this)->b << endl;
             // ^^^^^^^^^^^^^^^^^^^^^^^^    ^^^^^^^^^^^^^^^^^^^^^^^^
    }
};

I need to somehow allow parent to access child protected data, is it possible?

当然可以。这些需要是 public T的成员, 或者你需要制作 B<T>一个friendT :

class C : public B<C>
{
     friend class B<C>;
  // ^^^^^^^^^^^^^^^^^^
protected :
    static int a;
    static int b;
public :
    C() {
        print();
    }
}; 

Live Demo


friend声明仍然保留 class C 的封装, 同时打开对 class B<T> 中声明的特定接口(interface)的访问.

关于c++ - 家长访问 child 私有(private)/ protected ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898554/

相关文章:

c++ - 在派生类中调用多个虚函数

构造函数中的 C++ std::vector

python - Django 模板和应用程序未加载

java - 避免显式强制转换的最佳方法

c++ - 具有必要副作用的静态初始化被优化掉

c++ - 无法将模板化函数显式实例化为模板化类

C# 从工厂返回通用接口(interface)

c++ - C2143 : syntax error: missing ';' before '*' & C4430: missing type specifier - int assumed. 注意:C++ 不支持default-int

c++ - 如何将移动构造函数与二维数组 (**<type>) 一起使用?

c++ - 如何在 RAD Studio XE 中更改 TMsgDlgButtons "Yes"和 "No"按钮的文本?