简体   繁体   中英

Invoking the constructor of a member object of a class

I have two classes L1 and L2 and the definition of L2 includes L1 as a member object. Each of L1 and L2 has its own constructor. Obviously, when instantiating L2, its constructor must call L1's constructor. However, I don't know how to go about doing this. Here is a (failed) attempt along with the accompanying compiler error.

class L1
{
public:
  L1(int n)
      { arr1 = new int[n] ; 
        arr2 = new int[n];   }
private:
  int* arr1 ;
  int* arr2 ;  
};


class L2
{
public:
  L2(int m)  
    { in  =  L1(m) ; 
      out =  L1(m) ; }

private:
  L1 in ; 
  L1 out;

};

int main(int argc, char *argv[])
{
  L2 myL2(5) ;

  return 0;
}

The compilation error was:

[~/Desktop]$ g++ -g -Wall test.cpp             (07-23 10:34)
test.cpp: In constructor ‘L2::L2(int)’:
test.cpp:21:5: error: no matching function for call to ‘L1::L1()’
test.cpp:8:3: note: candidates are: L1::L1(int)
test.cpp:6:1: note:                 L1::L1(const L1&)
test.cpp:21:5: error: no matching function for call to ‘L1::L1()’
test.cpp:8:3: note: candidates are: L1::L1(int)
test.cpp:6:1: note:                 L1::L1(const L1&)

How do I go about fixing this code?

Use initialization list:

class L2
{
public:
  L2(int m) : in(m), out(m) //add this  
  {
  }

private:
  L1 in ; 
  L1 out;

};

Use constructor-initializer lists, eg:

L2(int m) : in(m), out(m) { }

Never use assignment when you should be using initialization.

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