依赖类作为其他类成员

Rom*_*n L 10 c++ constructor initialization operator-precedence ctor-initializer

我有一个类B需要A构造一个类的实例:

class B
{
    B(A* a); // there is no default constructor
};
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

有没有一种很好的方法来解决这个问题,而无需修改类AB?谢谢.

Fre*_*urk 7

有没有一种很好的方法可以在不修改A类和B类的情况下解决这个问题?

打开编译器警告 ; 对于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的工具来检测这一点.


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

他们为什么要这样做?我怀疑你太担心发生什么.即便如此,您也可以在课堂上发表评论:

A a;  // Must be listed before member 'b'!
B b;
Run Code Online (Sandbox Code Playgroud)

不要低估良好的评论力量.:)然后允许有意无视他们的人得到他们应得的东西; 毕竟你正在使用C++.


Naw*_*waz 5

使用名为Base-from-Member的众所周知的C++习语来解决这个问题.

将基类定义为,

class C_Base
{
    A a; //moved `A a` to the base class!
    C_Base() : a() {}
};

class C : public C_Base
{
    C() : b(&a) {}
    B b; // 1. initialized as b(&a) while "a" uninitialized
    //A a; // too late...
};
Run Code Online (Sandbox Code Playgroud)

现在,a保证在之前进行初始化b.