开发者

How can I initialize a reference attribute in my class

I have a class which has a private attribute which is a reference to another class:

class A {
public:
   A(); 
   A(B& anotherB);
private:
  B& bRef;
}

In my A(B& anotherB), I can do this:

  A:开发者_高级运维:A(B& anotherB)
   : bRef(anotherB) {
}

But what about A()? I tried this:

   A::A()
    : bRef(B()) {}

But I get this error 'error: invalid initialization of non-const reference of type ‘B&’ from a temporary of type ‘B’.

How can I call initialize B reference in A with the default constructor of B?

Thank you.


You have to have a real instance to initialize it to. Saying : bRef(B()) creates a temporary which is immediately destroyed, thus your reference would be to an object that no longer exists, thus the compiler error.

You don't need to initialize it unless you're making some decision based on it not being initialized. In that case you can have a bool initialized; member that you use to keep track of the state.

If you want to initialize it to something like NULL, use a pointer instead.


If you really, really want to use a reference but still keep your default constructor, you could set up a global (or file static) instance of B that represents a null or default state, whatever you want your default A to use.

A::A()
: bRef(nullB) {}


References always refer to valid objects. So, there is no way to initialize bRef without a valid B object.

Suggestion: Consider making A::A() private and not implementing it.


You should model your class with reference field if you know that the field always hold a valid reference. In your case you have default constructor which you want your reference to point to a dummy value, it should be more appropriate to model it with pointer field. You cant assign NULL to reference nor it should point to a object create on the stack and only valid within the scope.


With c++-11, you may build something like:

class A {
public:
   A(); 
   A(B& anotherB);
private:
  B& bRef = *(B*)(0);
  // Or assign bRef with an accessible ( static ) instance of `B` previously created elsewhere 
}

-- BUT : bRef being assigned a NULL pointer, You have the responsability to assign a valid instance of B as soon as you create an instance of A.

Be advised that this construct is a dangerous old-c style.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜