简体   繁体   中英

Initializing class object inside the other class constructor

I have a class, it names A and A class has 3 another class in its private.

class A{
    public:
          A();
          A(int num);
          A(C& mC, P& mP, M& mM, int num);
    //there is a getter and setter for all member this only one example(please check are they right?)
          M getM()const{return pM;} 
          void setM(M classM){ pM = classM ;}
        private:
            C& pC;
            P& pP;
            M& pM;
            int digit= 0;
        };

I'm doing that in parameter constucture:

A::A(C& mC, P& mP, M& mM, int num):pC(mc),pP(mP),pM(mM)
{
// doing someting here
}

But I can't write a code for default and first parameter constructure, when I write something compiler saying to me that :

error: uninitialized reference member in 'class A&' [-fpermissive] A::A(){

and

note: 'A& A::pP' should be initialized A& pP;

someting like this, several errors and notes.

What should I do? How can I initialize classes in default and first parameter constructure?

Class A contains references to other object. Unlike pointers, references cannot be null. To make this work, you either need to:

  • Use pointers instead of references, and initialize them to nullptr is no valid object is provided in the constructor
  • Store those members by value . This involves a copy of the original arguments, and different in semantics - might not be what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM