-1
Triny從網絡測驗,看到這段代碼。打印結果爲02當調用複製構造函數或賦值構造函數時?
這意味着默認複製構造函數用於列表初始化,而賦值構造函數用於矢量。爲什麼?
#include <algorithm>
#include <iostream>
#include <list>
#include <vector>
class Int
{
public:
Int(int i = 0) : m_i(i) { }
public:
bool operator<(const Int& a) const { return this->m_i < a.m_i; }
Int& operator=(const Int &a)
{
this->m_i = a.m_i;
++m_assignments;
return *this;
}
static int get_assignments() { return m_assignments; }
private:
int m_i;
static int m_assignments;
};
int Int::m_assignments = 0;
int main()
{
std::list<Int> l({ Int(3), Int(1) });
l.sort();
std::cout << (Int::get_assignments() > 0 ? 1 : 0);
std::vector<Int> v({ Int(2), Int() });
std::sort(v.begin(), v.end());
std::cout << (Int::get_assignments() > 0 ? 2 : 0) << std::endl;
return 0;
}