![]() |
#2
rjsp2022-10-25 15:30
|
写这个代码的目的是为了试set容器调用insert()方法存自定义类型数据的过程。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <set>
using namespace std;
//这个是存入set的对象
class MyInt{
public:
MyInt(int arg){
this->arg = arg;
cout << "构造" << endl;
}
MyInt(const MyInt& obj) {//必须加const
this->arg = obj.arg;
cout <<"拷贝构造" << endl;
}
~MyInt(){
cout << "析构" << endl;
}
public:
friend ostream& operator<<(ostream& out, MyInt s);
public:
int arg;
};
//重载<<运算符
ostream& operator<<(ostream& out, MyInt obj){
out << obj.arg << endl;
return out;
}
//
struct IntFunc {
//重载()
bool operator()(const MyInt& obj1, const MyInt& obj2) const{
if (obj1.arg < obj2.arg){
cout<< "重载()"<<endl;
return true;
}
else{
return false;
}
}
};
void FuncTest(){
set<MyInt, IntFunc> s;
MyInt num1(5);
MyInt num2(2);
s.insert(num1);
s.insert(num2);
set<MyInt, IntFunc>::iterator it = s.begin();
for (; it != s.end(); it++){
cout << *it;
}
}
int main()
{
FuncTest();
return 0;
}
下面是上面代码的运行结果:

运行结果:
构造 //创建num1对象调用构造函数
构造 //创建num2对象调用构造函数
拷贝构造 //insert()是先创建临时对象,然后把临时对象拷贝到容器里,调用拷贝构造函数
重载() //我都困惑是,(1)上一步不都已经调用拷贝构造把临时对象拷贝到容器里了吗?为什么又调用重载()了?这两个的调用顺序为什么反了?
重载() //(2)为什么这里又是先调用重载(),然后调用拷贝构造把临时对象拷贝到容器里?
拷贝构造
拷贝构造 //(3)为什么用for输出set里对象还要调用MyInt的拷贝构造?感觉就是调用也应该调用set的迭代器的拷贝构造呀!
2
析构
拷贝构造 //(4)为什么用for输出的时候还调用了2次?直接迭代器++,然后迭代器访问值不就行了,为什么还要再次调用拷贝构造?
5
析构
析构
析构
析构
析构
上面4个问题一直想不明白,希望大佬能帮助我解答一下,看看我的问题在哪里,帮我指点迷津。谢谢了!

