c++ - 为什么即使在调用参数化构造函数时也会调用默认构造函数?
问题描述
我有一个类,我正在使用参数化构造函数创建它的一个对象。在此期间,已调用参数化构造函数和默认构造函数。
这是我的片段:
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 名称:bob 年龄:25
键是:1 名称:raven 年龄:30
所以,我想明白,如果我在调用参数化构造函数,为什么在参数化构造函数之后调用了默认构造函数?
解决方案
因为如果指定的键不存在,std::map::operator[]
将首先插入一个默认构造的。然后从临时的like中分配student
插入的内容。student
student
student("bob", 25)
返回对映射到与 key 等效的键的值的引用,如果这样的键不存在,则执行插入。
你可以insert
改用。
students.insert({0, student("bob", 25)});
students.insert({1, student("raven", 30)});
推荐阅读
- amazon-web-services - Flask-WTF“CSRF 令牌不匹配”与 AWS ECS 和 ELB
- path - 有没有办法在 macOS 上重置 PATH 变量?
- python - matplotlib 制作线条而不是正常的散点图
- javascript - 地理位置 API
- amazon-web-services - 在 AWS CI-CD 管道中找不到 NVM
- ocaml - 如何将值提升到 monad
- material-ui - 如何在不知道是否启用深色主题的情况下获取当前的原色和二次色?
- javascript - audio.play() 给我“未捕获(承诺)DOMException 错误”
- javascript - 将 useStaticQuery 与 Gatsby 一起使用不会呈现所需的数据
- sql - 如何通过多列理想地组合具有不同主键的两个表 HASH