为什么即使我调用参数化构造函数也会调用默认构造函数?

Why does default constructor is called even when I am calling the parameterized constructor?

本文关键字:调用 构造函数 默认 参数 为什么      更新时间:2023-10-16

>我有一个类,我正在使用参数化构造函数创建它的对象。在此期间,已调用参数化构造函数和默认构造函数。

这是我的片段:

class student {
string name;
int age;
public:
student() {
cout << "Calling the default constructorn";
}
student(string name1, int age1) {
cout << "Calling the parameterized constn";
name = name1;
age = age1;
}
void print() {
cout << " name : " << name << " age : " << age << endl;
}
};
int main()
{
map<int, student> students;
students[0] = student("bob", 25);
students[1] = student("raven", 30);
for (map<int, student>::iterator it = students.begin(); it != students.end(); it++) {
cout << "The key is : " << it->first ;
it->second.print();
}
return 0;
}

当我执行此代码片段时,我的输出为:

调用参数化的 const
调用默认构造函数
调用参数化 const
调用默认构造函数
键是:0 名称:鲍勃年龄:25
键是:1 名称:乌鸦年龄:30

所以,我想了解,如果我调用参数化构造函数,为什么在参数化构造函数之后调用默认构造函数?

因为如果指定的键不存在,std::map::operator[]将首先插入默认构造的student。然后插入的student从临时student分配,如student("bob", 25)

返回对映射到等效键的值的引用,如果此类键尚不存在,则执行插入。

您可以改用insert

students.insert({0, student("bob", 25)});
students.insert({1, student("raven", 30)});
students[0]

使用默认构造函数自动构造对象。students[0] =使用复制赋值运算符,student("bob", 25)调用parameterized constructor

您可以使用:

studets.insert(pair<int, student>(0, student("bob", 25)));

或:

studets.emplace(0, student("bob", 25));

避免使用默认构造函数。

从标准:

T& operator[](const key_type& x);

效果:相当于:返回try_emplace(x(.第一>秒;

T& operator[](key_type&& x);

效果:相当于:返回try_emplace(移动(x((.第一>秒;

T&       at(const key_type& x);
const T& at(const key_type& x) const;

返回:对对应于 x in* *this 的mapped_type的引用。

抛出:类型 out_of_range 的异常对象(如果不存在此类元素(。

复杂度:对数。