![](/img/trans.png)
[英]“No appropriate default constructor available”--Why is the default constructor even called?
[英]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.