加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c依赖类作为其他类成员

发布时间:2020-12-16 06:03:25 所属栏目:百科 来源:网络整理
导读:我有一个类B需要构建一个类A的实例: class B{ B(A* a); // there is no default constructor}; 现在我想创建一个包含B作为成员的类,所以我还需要添加A作为成员并提供给B的构造函数: class C{ C() : a(),b(a) {} A a; // 1. initialized as a() B b; // 2.
我有一个类B需要构建一个类A的实例:
class B
{
    B(A* a); // there is no default constructor
};

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

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

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

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

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

解决方法

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

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

cc1plus: warnings being treated as errors
t.cpp: In constructor 'A::A()':
Line 3: warning: 'A::y' will be initialized after
Line 3: warning:   'int A::x'
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…

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读