vector容器几个疑惑点:
①初始化:
Dog.h
#ifndef __test_header__Dog__
#define __test_header__Dog__
#include <stdio.h>
#include <string>
class Dog{
public:
Dog();
Dog(const char name[]);
bool operator==(const Dog &dog) const;
Dog(const Dog &dog);
Dog(Dog &dog);
private:
std::string name;
};
#endif
Dog.cpp
#include "Dog.h"
#include <iostream>
using namespace std;
Dog::Dog(){
cout<<"Dog()"<<endl;
};
Dog::Dog(const char name[]) {
cout<<"Dog(const char name[])"<<endl;
this->name = name;
cout << this->name << endl;
};
Dog::Dog(Dog &dog){
this->name = dog.name;
cout<<"Dog(Dog &dog)"<<endl;
};
Dog::Dog(const Dog &dog){
this->name = dog.name;
cout<<"Dog(const Dog &dog)"<<endl;
};
bool Dog::operator==(const Dog &dog) const{
return dog.name == this->name;
};
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Dog.h"
using namespace std;
int main(int argc, const char * argv[]) {
Dog dog("sasa");
vector<Dog>v1{dog};
return 0;
}
输出的情况为:
很奇怪,为什么会调用2次拷贝构造函数呢?而且第一次调用的拷贝构造函数还是不带const关键字的那个
此时联想到之前一篇分析拷贝构造函数带与不带const区别的博客,将main函数中的第一句改写为const Dog dog("sasa");发现输出如下:
这次2次都是调用的带const的拷贝构造函数了,所以我猜想第一次调用拷贝构造函数是在初始化第一阶段,先用拷贝初始化的方式初始化一个Dog对象,是否调用带const的拷贝构造函数取决于拷贝初始化=号右边的值是不是const的,当这个对象被构造好了之后,vector再调用push_back函数将这个对象加入到容器中,而在push_back函数里又需要再调用一次拷贝构造函数,在vector中保存一份Dog对象的副本。而由于push_back函数的形参是const类型的,所以在push_back函数中调用的一定是带const的拷贝构造函数。
② 判断相等:
要想对两个vector进行比较,要求vector模板的参数类型重载了==操作符,如果没有重载,则不能够对两个vector进行比较,如果重载了==操作符,则比较的方式是:从第一个元素开始,比较相同位置的dog对象是否相等(dog重载了==操作符),以此类推,直到找到第一个不相等的对象,则两个容器不相等,如果相同位置的元素都相等,则容器也相等。