调用类的成员对象的构造函数
Invoking the constructor of a member object of a class
我有两个类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) { }
当您应该使用初始化时,切勿使用赋值。
相关文章:
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- c++构造函数成员初始化:传递参数
- 使用向量初始化参数化构造函数的对象数组
- C++定义构造函数使对象成为非 POD
- 通过向构造函数其他对象引用页面来创建对象
- 在没有复制构造函数的对象的成员函数中启动 std::thread
- C++将带有重载构造函数的对象添加到另一个对象
- 解释了构造函数成员初始化列表
- 在C++面向对象程序中,谁负责删除传递给构造函数的对象
- 关于默认构造函数,对象初始化/使用C++ OOP
- C++ 创建不带默认构造函数的对象数组
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 对已删除其复制构造函数的对象的向量进行迭代 (C2280)
- 不带初始值设定项的构造函数列表,其中包含带有已删除构造函数的对象
- C++中构造函数的对象初始化出现问题
- 是否可以反序列化(从原始内存块)没有默认构造函数的对象?
- 没有默认构造函数的对象成员的 wig setter
- 复制构造函数错误:对象的类型限定符与成员函数不兼容
- 构造函数和对象的成员变量初始化
- 类成员是需要构造函数的对象.它需要一个函数来实例化