c依赖类作为其他类成员

前端之家收集整理的这篇文章主要介绍了c依赖类作为其他类成员前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个类B需要构建一个类A的实例:
  1. class B
  2. {
  3. B(A* a); // there is no default constructor
  4. };

现在我想创建一个包含B作为成员的类,所以我还需要添加A作为成员并提供给B的构造函数

  1. class C
  2. {
  3. C() : a(),b(&a) {}
  4. A a; // 1. initialized as a()
  5. B b; // 2. initialized as b(&a) - OK
  6. };

但是问题是如果有人偶尔改变类中的变量定义的顺序,它会中断

  1. class C
  2. {
  3. C() : a(),b(&a) {}
  4. B b; // 1. initialized as b(&a) while "a" uninitialized
  5. A a; // too late...
  6. };

有没有一个很好的方法解决这个,而不修改A和B类?谢谢.

解决方法

Is there a good way to resolve this without modifying the classes A and B?

打开compiler warnings;对于gcc,这是-Wreorder(包含在-Wall中):

  1. cc1plus: warnings being treated as errors
  2. t.cpp: In constructor 'A::A()':
  3. Line 3: warning: 'A::y' will be initialized after
  4. Line 3: warning: 'int A::x'
  5. Line 2: warning: when initialized here

或者,使用类似lint的工具来检测.

But the problem is that if someone occasionally changes the order of the variables definition in the class…

他们为什么这么做?我怀疑你对可能发生的事情太担心了.即使如此,您也可以在课堂上发表评论

  1. A a; // Must be listed before member 'b'!
  2. B b;

不要低估良好评论的力量. :)然后让有意忽略他们的人得到应得的东西;毕竟,你使用C.

猜你在找的C&C++相关文章