文章目录
- 原因
- 关键代码
- 测试代码
- 错误
- 结论
- 疑问:为什么在c++中初始化数组的时候会调用构造函数?明明初始化是一个空数组!(希望有大佬可以评论区回答一下,我还没找到答案)
- 附页
踩坑记录,类模版中无法初始化导致报错
原因
关键代码
这里使用了template,用泛型去表达传入参数类型。
主要问题在于 this->pAddress = new T[this->m_Capacity];
这一句
template<class T>
class MyArray {
public://初始化容量 有参构造//explicit标记是构造函数不会做隐式转化explicit MyArray(int m_capacity) {std::cout << "构造函数执行" << endl;this->m_Size = 0;this->m_Capacity = m_capacity;//主要问题在这this->pAddress = new T[this->m_Capacity];}private:T *pAddress; //指针指向堆区开辟的地址int m_Capacity; //数组容量int m_Size;
};
测试代码
MyArray<int> arra1(5);
测试使用int基本类型没有问题
使用泛型为类(非基本类型时报错)
//测试自定义数据类型
class Person {
public:// Person() = default;Person(const string name, int age): name(name),age(age) {}string name;int age;
};int main(int argc, char *argv[]) {// MyArray<int> arra1(5);// for (int i = 0; i < 5; ++i) {// //尾插法,插入数据// arra1.Push_Back(i);// }// print(arra1);// cout << "容量:" << arra1.m_capacity() << endl;MyArray<Person> arra1(10);for (int i = 0; i < 5; ++i) {//尾插法,插入数据string name = "张三";Person p1(name.append(std::to_string(i)), 10 * i);arra1.Push_Back(p1);}print(arra1);cout << "容量:" << arra1.m_capacity() << endl;cout << "大小:" << arra1.m_size() << endl;
}
错误
从前面可以看到是MyArray构造函数调用出错,说明是Person p1(name.append(std::to_string(i)), 10 * i);
调用这一行出现问题。
继续看下面报错,错误指向Person构造函数参数不够!
查看代码,果然没写无参构造函数,当加上Person() = default;
就不会出现问题。
In file included from /Users/mac/CLionProjects/stl/main.cpp:3:
/Users/mac/CLionProjects/stl/MyArray.hpp:20:30: error: no matching constructor for initialization of 'Person[]'this->pAddress = new T[this->m_Capacity];^
/Users/mac/CLionProjects/stl/main.cpp:42:21: note: in instantiation of member function 'MyArray<Person>::MyArray' requested hereMyArray<Person> arra1(10);^
/Users/mac/CLionProjects/stl/main.cpp:7:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
class Person {^
/Users/mac/CLionProjects/stl/main.cpp:7:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided
/Users/mac/CLionProjects/stl/main.cpp:11:5: note: candidate constructor not viable: requires 2 arguments, but 0 were providedPerson(const string name, int age)^
1 error generated.
结论
说明在初始化Tthis->pAddress = new T[this->m_Capacity];
的时候是会调用对应类的构造函数的。
添加上构造函数解决问题!
疑问:为什么在c++中初始化数组的时候会调用构造函数?明明初始化是一个空数组!(希望有大佬可以评论区回答一下,我还没找到答案)
附页
C++中若类中没有默认构造函数,如何使用对象数组