c++ - 为什么即使在调用参数化构造函数时也会调用默认构造函数?

标签 c++ class stdmap default-constructor

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

这是我的代码片段:

class student {
    string name;
    int age;
public:
    student() {
        cout << "Calling the default constructor\n";
    }
    student(string name1, int age1) {
        cout << "Calling the parameterized const\n";
        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 名字:raven 年龄:30

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

最佳答案

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

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

您可以使用 insert相反。

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

关于c++ - 为什么即使在调用参数化构造函数时也会调用默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62484256/

相关文章:

objective-c - objective c 将一个对象设置为一个未知的类

c++ - 如何创建一个计时器重复运行我的程序? C++

c++ - fwrite 字符串中的二进制数据

c++ - 海合会 LTO : Limit scope of optimization

c++ - QT 和 C++ : can't call function outside main() function

c++ - std::map operator [] - 未定义的行为?

c++ - 你如何找出安装在 AIX 机器上的 xlC 的版本

c++ - 我应该在 C++ 的类中存储引用吗?

c++ - 放置到 std::map 的 std::map

c++ - 一个偶尔的作家,多个 std::map 的常客