调用类的成员对象的构造函数

Invoking the constructor of a member object of a class

本文关键字:构造函数 成员对象 调用      更新时间:2023-10-16

我有两个类L1和L2,L2的定义包括L1作为成员对象。L1和L2中的每一个都有自己的构造函数。显然,在实例化L2时,其构造函数必须调用L1的构造函数。然而,我不知道该怎么做。这是一次(失败的)尝试以及伴随的编译器错误。

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;
}

编译错误为:

[~/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&)

我该如何修复此代码?

使用初始化列表:

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

使用构造函数初始值设定项列表,例如:

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

当您应该使用初始化时,切勿使用赋值。