C ++原型初始化列表?

时间:2011-09-18 14:36:26

标签: c++ class reference

如果我有以下代码(问题的简化版):

class TestA
{
    public:
    int A,B,C;

    TestA(){A = 1; B = 5; C = 10;}
};

//This is a referencing class to allow for universal and consistent operations
class TestB
{
   public:
   int &A, &B, &C; //Note references

   TestB(TestA &A) : A(A.A), B(A.B), C(A.C){}; //This is fine
   TestB(TestC &C) : A(C.A), B(C.B), C(C.C){}; //This needs to be prototyped
};

//Similar class to TestA but in the main program would have...
//...many different and conflicting variables and has to be treated as stand alone
class TestC
{
    public:
    int A, B, C;
    int Size;

    void Function()
    {
        TestB B(*this); //This uses TestB. TestB cannot be prototyped. 
        //etc etc
    }
};

我想知道,是否有可能对基于初始化列表的构造函数进行原型设计?

如果没有,有什么替代方案?请记住,必须立即初始化参考文献。

3 个答案:

答案 0 :(得分:2)

如果要单独声明和定义具有成员初始化列表的构造函数:

struct B;              // <-- (forward declaration of B)
struct A {
   A(B& b);            // <-- A ctor declaration
   B& b;
};

struct B {             // <-- (real definition of B)
   A a;
};

A::A(B& b) : b(b) {};  // <-- A ctor definition (with member-initialiser!)

成员初始化列表与定义一致,而不是声明。

答案 1 :(得分:1)

如果通过“原型设计”表示功能声明和定义的分离,这应该有效:

class TestB {
   // ...
   TestB(TestC &C);
};

TestB::TestB(TestC &C) : A(C.A), B(C.B), C(C.C) {
};

答案 2 :(得分:1)

原始问题已经得到解答,但我无法对设计发表评论。

这三个类彼此完全相爱.. :) ..我的意思是不需要的循环依赖和紧耦合等等。

为什么不让TestC和TestA扩展TestB?

假设你有充分的理由不这样做,其他选择就是:

阅读代码中的评论

class TestX
{
public:
    int A,B,C;

    TestX()
    {
        A = 1;
        B = 5;
        C = 10;
    }
};

// "int A,B,C;" coming from baseclass now.
class TestA : public TestX {};

// fwd decl not needed anymore.
// class TestC;

class TestB
{
public:
    int &A, &B, &C; //Note references

    // dealing with TestX instead.
    TestB(TestX &X) : A(X.A), B(X.B), C(X.C) {};
};

class TestC : public TestX
{
public:
    // coming from baseclass now
    // int A,B,C;
    int Size;

    void Function()
    {
        // moved out to some other place.. main() in this case.
        // TestB B(*this);
    }
};

// not needed anymore..
// TestB::TestB(TestC &C): A(C.A), B(C.B), C(C.C) {}

int main ()
{
    TestC c;
    TestA a;

    TestB bc(c);
    TestB ba(a);

    // your primary usecase (referencing class to allow for universal and consistent operations)
    // is satisfied, without changing anything in the client code.
    // You can still use c as TestC where "int Size" or "Function" are needed.

    return 0;
}

现在依赖关系是:

X <---- A
^   |__ C
|
B