Dog.h
#ifndef __test_header__Dog__
#define __test_header__Dog__
#include <stdio.h>
#include <string>
class Dog{
public:
Dog();
Dog(const char name[]);
const Dog& operator=(const Dog &dog) const;
bool operator==(const Dog &dog) const;
Dog(const Dog &dog);
std::string getName();
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(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;
};
const Dog& Dog::operator=(const Dog &dog) const {
cout<<"operator="<<endl;
return *this;
};
string Dog::getName(){
return 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("haha");
Dog dogs[2];
dogs[0] = dog;
dogs[1] = dog;
cout << dogs[0].getName() << endl;
return 0;
}
输出如下:
可以看到数组在声明时会根据数组指定的大小去调用无参的拷贝构造函数构造出Dog数组中得元素,然后在复制时会调用重写后的=运算符来实现赋值操作,如果没有重载=运算符,则执行的是默认的按位拷贝操作。
如果将数组改为列表初始化的方式,如下:
Dog dogs[2] = {"haha", "sasa"};
那么数组的构造将调用带参数类型的构造函数来构造数组。