【问题标题】:How make hierarchy of friend classes?如何制作朋友等级的层次结构?
【发布时间】:2010-12-19 10:43:31
【问题描述】:

我有class A,它只有私有成员(包括数据、方法、构造函数、析构函数......)。我还有class Bclass A 的朋友。我希望 B 的所有派生类(也有从 B 继承的模板)也成为 class A 的朋友。有没有办法做到这一点?

【问题讨论】:

  • 是的。将成员设为 protected 而不是 private
  • 因为我不希望其他类期望 B(和派生)可以创建和管理 A 类型的实例。
  • @Billy,这行得通吗?将它们设为私有将允许访问 A 的派生类,而不是 B(朋友的)。
  • @Sergey:我误解了这个问题。
  • @Sergey:你写的 Billys 的建议不起作用。

标签: c++ templates inheritance


【解决方案1】:

C++ 不直接支持这个:"a kid of my friend is not my friend"

你必须使用另一种方式来实现它;例如,在class B中定义一组受保护的访问器函数:

class A {friend class B; int x, y};

class B
{
protected:
    int& AccessX(A& a) {return a.x;}
    int& AccessY(A& a) {return a.y;}
}

这只有在class A 非常小时才可行。

如果class A 很大,您将不得不考虑您究竟希望class B 及其派生类与class A 做什么,并将其表示为一组函数。将这些定义为class B 中的受保护函数:

class A
{
    A(): x(42), y(99) {}
    friend class B;
    int x, y;
}

class B
{
protected:
    A Create() {return A();}
    void Manage(A& object) {object.x += 1; object.y += 2;}
}

【讨论】:

  • 将访问函数设为静态是有意义的,因为它们不使用 B 类中的任何内容。
猜你喜欢
  • 1970-01-01
  • 2011-04-17
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多