繁体   English   中英

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

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

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

这是我的片段:

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;
}

当我执行这个片段时,我的 output 如下:

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

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

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

返回对映射到与 key 等效的键的值的引用,如果这样的键不存在,则执行插入。

您可以改用insert

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

student students[0]正在使用它的默认构造函数自动构造 object。 student 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);

效果:相当于:return try_emplace(x).first->second;

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

效果:相当于:return try_emplace(move(x)).first->second;

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

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

抛出:如果不存在此类元素,则异常 object 类型为 out_of_range。

复杂性:对数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM