Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 调用类的成员对象的构造函数_C++_Constructor - Fatal编程技术网

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

C++ 调用类的成员对象的构造函数,c++,constructor,C++,Constructor,我有两个类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

我有两个类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) { }

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

使用成员初始值设定项。在构造函数主体开始之前,它正在调用
:in(),out()